Friday, September 18, 2015

LeetCode [283] Move Zeroes

283. Move Zeroes
Easy

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.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int n = nums.size(), i = 0, j = 0;
        while(j<n){
            while(j<n && nums[j]==0) j++;
            if(j<n) nums[i++] = nums[j++];
        }
        while(i<n){
            nums[i++] = 0;
        }
    }
};

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int n = nums.size();
        int i = 0, j = 0;
        
        while(j<n){
            while(j<n && nums[j]==0){ 
                j++;
            }
            while(j<n && nums[j]!=0){
                nums[i++] = nums[j++];
            }
        }
        fill(nums.begin()+i, nums.end(), 0);
    }
};

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public void moveZeroes(int[] nums) {
        int n = nums.length;
        int i = 0, j = 0;
        while(i<n){
            if(nums[i]==0){
                i++;
            }else{
                nums[j] = nums[i];
                i++;
                j++;
            }
        }
        
        while(j<n){
            nums[j] = 0;
            j++;
        }
    }
}

No comments:

Post a Comment