You are given a 0-indexed array nums
of size n
consisting of non-negative integers.
You need to apply the following operations until the array cannot be changed further:
nums[i] == nums[i + 1]
for some i
(0 <= i < n - 1), then set nums[i] = 2 * nums[i]
and nums[i + 1] = 0
.0
s to the end of the array.Return the resulting array after applying the above operations.
Input: nums = [1,2,2,1,1,0]
Output: [1,4,2,0,0,0]
nums
?
1 <= nums.length <= 10^4
. Let’s assume it is reasonable for typical in-memory processing.nums
?
nums[i] == nums[i + 1]
), we update nums[i]
to 2 * nums[i]
and set nums[i + 1]
to 0.def applyOperations(nums):
n = len(nums)
# Apply the specified operations
for i in range(n - 1):
if nums[i] == nums[i + 1] and nums[i] != 0:
nums[i] = 2 * nums[i]
nums[i + 1] = 0
# Shift all zeroes to the end
result = [num for num in nums if num != 0]
result += [0] * (n - len(result))
return result
# Example Usage
nums = [1, 2, 2, 1, 1, 0]
print(applyOperations(nums)) # Output: [1, 4, 2, 0, 0, 0]
Thus, the overall time complexity is O(n), where n
is the length of the input array.
We have designed the solution to be efficient and straightforward, ensuring that the operations are performed in linear time.
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?