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, nums should 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.
********记录最新的非0 的位置 ********** 先走一遍,再在后半部分置零************
public class Solution {
public void moveZeroes(int[] nums) {
int nonZero = 0;
for(int i=0 ;i<nums.length;i++)
if(nums[i] != 0)
nums[nonZero++] = nums[i];
for(;nonZero<nums.length;nonZero++)
nums[nonZero] = 0;
}
}
******** 只走一遍, 记录第一个0 的位置,每次分情况展开************
public class Solution {
public void moveZeroes(int[] nums) {
int i0 = -1;
for(int i =0; i<nums.length; i++){
if(nums[i] == 0){
if(i0<0)
i0 = i;
}else{
if(i0 >=0){
nums[i0] = nums[i];
nums[i] = 0;
i0++;//update i0 to the next position
while(i0<=i && nums[i0]!=0)
i0++;
}
}
}
}
}
Note:
No comments:
Post a Comment