Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function,numsshould be[1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
My solution:
后記:2019.5.11
再看當年的筆記,有幾點體會,特記錄一下:
- 當年還不知道Two pointer的套路,寫出的代碼有夠暴力,居然循環嵌套循環。再不濟也應該用個ArrayList記錄一下非零的元素,再復制回原數組?
- 當年代碼的style有點問題,操作符和變量之間沒有空格。
- 當年并沒有寫一些文字解釋自己的代碼或者別人的解法,或者在code中加入注釋。這樣其實不利于自己深入理解代碼,日后看起來也比較費力。自己以后需要多注意啊。
public class Solution {
public void moveZeroes(int[] nums) {
int counter = 0;
for(int i=0; i<nums.length-1; i++) {
if (nums[i] == 0) {
counter++;
}
}
while(counter>0){
for(int i=0; i<nums.length-1; i++) {
if (nums[i] == 0) {
nums[i] = nums[i+1];
nums[i+1] = 0;
}
}
counter--;
}
}
}
我的解法效率很低,只有3.5%
附一個高明的 code。
下面是我自己對code的理解(2019.05.11)
這個解法其實是利用了Two pointers的套路。
- index 指針的物理意義是其左邊的元素為非零的元素。
- 第一個循環結束后,所有的非零元素都被放到了index左邊。第二個循環將index到數組末端的元素設置為零即可。
public class Solution {
public void moveZeroes(int[] nums) {
int index = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] != 0){
nums[index++] = nums[i];
}
}
for(int i = index; i < nums.length; i++) {
nums[i] = 0;
}
}
}
效率是87.33%, unbelievable.