Leetcode 2460. Apply Operations to an Array
You are given a 0-indexed
array nums
of size n
consisting of non-negative integers.
You need to apply n - 1
operations to this array where, in the i-th (0 <= i < n - 1)
operation, you will apply the following on the i-th
element of nums
:
nums[i] == nums[i + 1]
, then assign the value of nums[i]
to 2 * nums[i]
, and set nums[i + 1]
to 0
.After completing all the operations, shift all 0's
to the end of the array.
Return the resulting array.
nums[i] == nums[i + 1]
).Here’s the implementation of the stated strategy:
public class Solution {
public int[] applyOperations(int[] nums) {
int n = nums.length;
// Apply operations (nums[i] == nums[i + 1])
for (int i = 0; i < n - 1; i++) {
if (nums[i] == nums[i + 1]) {
nums[i] *= 2;
nums[i + 1] = 0;
}
}
// Create an array to store the result
int[] result = new int[n];
int index = 0; // Index for the result array
// Add all non-zero elements from the modified nums to result
for (int num : nums) {
if (num != 0) {
result[index++] = num;
}
}
// The rest of the elements will be zero by default (as array initialized to zeros)
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
// Test example
int[] nums = {1, 2, 2, 1, 1, 0};
int[] result = sol.applyOperations(nums);
// Print the result
for (int num : result) {
System.out.print(num + " ");
}
}
}
Therefore, the overall time complexity is O(n), where n
is the length of the input array. This is optimal given that we need to process each element at least once.
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?