Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pick indices #23

Open
ishu9bansal opened this issue Jan 26, 2024 · 1 comment
Open

Pick indices #23

ishu9bansal opened this issue Jan 26, 2024 · 1 comment

Comments

@ishu9bansal
Copy link
Owner

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
Copy link
Owner Author

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;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant