283. Move Zeroes

description: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]

require:You must do this in-place without making a copy of the array.
Minimize the total number of operations.

First Edition

class Solution {
    public void moveZeroes(int[] nums) {
        int i = 0;
        for(int j = 0; j < nums.length; j++) {
            if(nums[j] != 0) {
                nums[i++] =nums[j];
            }
        }
        for (int k = i; k < nums.length; k++) {
            nums[k] = 0;
        }
    }
}

SECOND EDITION

class Solution {
    public void moveZeroes(int[] nums) {
        int i = 0;
        int len = nums.length;
        for(int j = 0; j < len; j++) {
            if(nums[j] != 0) {
                nums[i++] =nums[j];
            }
        }
        for (int k = i; k < len; k++) {
            nums[k] = 0;
        }
    }
}

Runtime: 1 ms, faster than 100.00% of Java online submissions for Move Zeroes.

THIRD EDITION

class Solution {
    public void moveZeroes(int[] nums) {
        int i = 0;
        int len = nums.length;
        for(int j = 0; j < len; j++) {
            if(nums[j] != 0) {
                int temp = nums[j];
                nums[j] = nums[i];
                nums[i] = temp;
                i++;
            }
        }
    }
}

Runtime: 1 ms, faster than 100.00% of Java online submissions for Move Zeroes.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章