Sunday, January 1, 2017

Move Zeroes

Q;
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:
  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.
A:
********记录最新的非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