Open ishu9bansal opened 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;
}
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: