Leetcode 2460. Apply Operations to an Array
Given an array nums
of size n
, you need to apply the following operations:
i
from 0
to n-2
(inclusive), check if nums[i]
is equal to nums[i+1]
. If they are equal, set nums[i]
to 2 * nums[i]
and nums[i+1]
to 0
.0
s to the end of the array while maintaining the relative order of the non-zero elements.Return the resulting array after the operations have been applied.
Given input nums = [1, 2, 2, 1, 1, 0]
:
[1, 4, 0, 2, 0, 0]
[1, 4, 2, 0, 0, 0]
The overall time complexity is O(n)
:
#include <vector>
std::vector<int> applyOperations(std::vector<int>& nums) {
int n = nums.size();
// Step 1: Apply the operations to combine equal elements.
for (int i = 0; i < n - 1; ++i) {
if (nums[i] == nums[i + 1]) {
nums[i] = nums[i] * 2;
nums[i + 1] = 0;
}
}
// Step 2: Move all zeros to the end.
std::vector<int> result;
result.reserve(n);
// Add non-zero elements first.
for (int i = 0; i < n; ++i) {
if (nums[i] != 0) {
result.push_back(nums[i]);
}
}
// Add zeros at the end.
while (result.size() < n) {
result.push_back(0);
}
return result;
}
result
to put all non-zero elements in their original relative order and then append zeros until the array has the same length as the original nums
.This approach ensures that we efficiently transform and rearrange the elements within the given array while maintaining a linear time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?