283. Move Zeroes

 

 

class Solution {
    public void moveZeroes(int[] nums) {
        int slow = 0;
        int fast = 0;
        while(fast < nums.length){
            if(nums[fast] == 0){
                fast++;
            }else{
                nums[slow] = nums[fast];
                slow++;
                fast++;
            }
        }
        if(slow == nums.length) return;
        
        for(int i = slow; i < nums.length; i++){
            nums[i] = 0;
        }
        
    }
}




class Solution {
    public void moveZeroes(int[] nums) {
        int i = 0;
        int j = nums.length - 1;
        while(i < j){
            while(i < nums.length && nums[i] != 0){ // boundary 
                i++;
            }
            while(j >= 0 && nums[j] == 0){ // boundary 
                j--;
            }
            
            swap(nums, i, j);
            i++;
            j--;
        }
        
    }
    private void swap(int[] nums, int i , int j){
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;

    }
}

 

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.

Example:

Input: [0,1,0,3,12]
Output: [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.

posted on 2018-07-18 08:44  猪猪&#128055;  阅读(102)  评论(0)    收藏  举报

导航