ishu9bansal / ideone

useful pieces of codes
1 stars 1 forks source link

Pick indices #23

Open ishu9bansal opened 8 months ago

ishu9bansal commented 8 months ago

This is very similar to a filter array method. But this is much useful, with some added functionality. If we think the indices as pointers between the elements then it also gives us clear distinction when dealing with ranges in an array.

Use this submission as an example to set up something like this , and use something useful

https://leetcode.com/submissions/detail/1157513853/

Adding the code block for the same for faster code copying:

template <class T>
vector<int> pickIndices(const vector<T>& v, function<bool(const vector<T>&, int)> predicate) {
    vector<int> ans;
    for(int i=0; i<=v.size(); i++)
        if(predicate(v,i))
            ans.push_back(i);
    return ans;
}
bool isSorted(vector<int>& v) {
    vector<int> kinks = pickIndices<int>(v,
        [](const vector<int>& v, int i) -> bool {
               if(i>=v.size() || i<=0) return false;
               return v[i]<v[i-1];
           });
    return kinks.empty();
}
ishu9bansal commented 8 months ago

https://leetcode.com/problems/find-if-array-can-be-sorted/submissions/1157221734/

see this submission as well! This tries to group the elements of the array based on the element properties.

vector<int> group(vector<int> &v){
        // general algo to group things together
        // arr elements:    1 1 2 2 2 3 3 3 4 4
        // grouping:           ^     ^     ^   ^
        // indices:        0 1 2 3 4 5 6 7 8 9 10
        // return array:    2 5 8 10
        vector<int> ans;
        int n = v.size();
        int i = n;
        int p = -1;    // initialize boundaries
        int c;
        while(i--){
            c = countBits(v[i]);
            if(c==p)    ans.back() = i;
            else    ans.push_back(i);
            p = c;
        }
        if(ans.size())  ans.pop_back(); // handling n == 0
        reverse(ans.begin(),ans.end());
        ans.push_back(n);
        return ans;
    }