2460: Apply-Operations-to-an-Array
Easy
table of contents
The key to this question is to track the prev
element, so we know when we have to apply the
operation. Our plan is to sort all the non-zero
elements first, before iterating through the remaining elements in the
array and setting them equal to zero.
To do this, we initialise prev = -1
and
index = 0
, to track where the next element should be
placed, before iterating through the entire array:
Now, if index != nums.size()
, that implies that there
still exists 0
elements that have not been shifted to the
end yet. Therefore, we can finish the question by setting all the
remaining elements to 0
.
code
class Solution {
public:
<int> applyOperations(vector<int>& nums) {
vectorint index = 0;
int prev = -1;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] != 0) {
if (prev != nums[i]) {
= nums[i];
prev [index++] = prev;
nums} else if (prev == nums[i]) {
[index-1] *= 2;
nums= -1;
prev }
} else {
= -1;
prev }
}
for (; index < nums.size(); ++index) {
[index] = 0;
nums}
return nums;
}
};