Given an array
nums
, write a function to move all0
'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,nums
should be[1, 3, 12, 0, 0]
.
給定一個num數(shù)組,把數(shù)組中的0都移動到最后去
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
不允許復制這個數(shù)組要在數(shù)組本身操作
My Solution
(Java) Version 1 Time: 20ms:
第一思路就是從前往后遍歷,找到第一個為0的位置,就讓它和后面第一個不為0的位置交換,這樣就可以把后面所有的非0交換到前面來
public class Solution {
public void moveZeroes(int[] nums) {
if(nums.length==0||nums.length==1)return;
for(int i=0;i<nums.length-1;i++){
if(nums[i]==0){
int j=0;
for(j=i+1;j<nums.length;j++){
if(nums[j]!=0){
nums[i]=nums[j];
nums[j]=0;
break;
}
}
}
}
return;
}
}
(Java) Version 2 Time: 0ms:
回頭轉(zhuǎn)念一想就覺得不對,既然要0放到最后,那何必搞兩次遍歷,直接把不是0的元素按照1234在前面排一列就是了,然后就有了這個0ms的方法
public class Solution {
public void moveZeroes(int[] nums) {
if(nums.length==0||nums.length==1)return;
int i=0,j=0,temp;
for(i=0;i<nums.length;i++){
if(nums[i]!=0){
temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
j++;
}
}
}
}
這兩個方法也是discuss里面的大多數(shù)的兩種方案,更慢的就不看了