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 ith operation (0-indexed ), you will apply the following on the ith element of nums:
- If
nums[i] == nums[i + 1], then multiplynums[i]by2and setnums[i + 1]to0. Otherwise, you skip this operation.
After performing all the operations, shift all the 0's to the end of the array.
- For example, the array
[1,0,2,0,0,1]after shifting all its0's to the end, is[1,2,1,0,0,0].
Return the resulting array.
Note that the operations are applied sequentially, not all at once.
Example 1:
Input: nums = [1,2,2,1,1,0]
Output: [1,4,2,0,0,0]
Explanation: We do the following operations:
- i = 0: nums[0] and nums[1] are not equal, so we skip this operation.
- i = 1: nums[1] and nums[2] are equal, we multiply nums[1] by 2 and change nums[2] to 0. The array becomes [1,4,0,1,1,0].
- i = 2: nums[2] and nums[3] are not equal, so we skip this operation.
- i = 3: nums[3] and nums[4] are equal, we multiply nums[3] by 2 and change nums[4] to 0. The array becomes [1,4,0,2,0,0].
- i = 4: nums[4] and nums[5] are equal, we multiply nums[4] by 2 and change nums[5] to 0. The array becomes [1,4,0,2,0,0].
After that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0].
Example 2:
Input: nums = [0,1]
Output: [1,0]
Explanation: No operation can be applied, we just shift the 0 to the end.
Constraints:
2 <= nums.length <= 20000 <= nums[i] <= 1000
题目又臭又长,简而言之就是先给数组操作一番,然后把所有非零元素移到前面,0移到后面。
前面的操作没啥好说的。后面移0们依旧是双指针。
根据27的经验,用了俩指针,一个slow从0开始,一个fast从1开始。如果slow已经是非零了就++,如果slow是0但是fast不是0就交换且slow++。不管咋样都要fast++遍历。其实自己也想的不是那么清楚,试了几次以后才过。
后来看了答案,比我自己写的简单。一个nonZero表示在这个元素之前的全是非0(注意是之前,而不是它和它之前),另一个i从0开始遍历。直接考虑在遍历的那个i,如果它不是0,那就把nonZero设成它,此时当然需要nonZero++。因为i一直在遍历所以不管怎样都要++。最后,i遍历完了以后因为我们没有把后面的重新assign成0,所以需要把nonZero及其后面的都设成0。
class Solution {
public int[] applyOperations(int[] nums) {
int i = 0;
while (i < nums.length - 1) {
if (nums[i] == nums[i + 1]) {
nums[i] *= 2;
nums[i + 1] = 0;
}
i++;
}
int nonZero = 0; // elements before this are nonZero
i = 0;
while (i < nums.length) {
if (nums[i] != 0) {
nums[nonZero] = nums[i];
nonZero++;
}
i++;
}
while (nonZero < nums.length) {
nums[nonZero] = 0;
nonZero++;
}
// original:
// int slow = 0;
// int fast = 1;
// while (fast < nums.length) {
// if (nums[slow] != 0) {
// slow+;
// }
// if (nums[slow] == 0 && nums[fast] != 0) {
// nums[slow] = nums[fast];
// nums[fast] = 0;
// slow++;
// }
// fast+;
// }
return nums;
}
}