283 Move Zeroes

ref: 283. Move Zeroes

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.

分析

非常不要脸地做一个easy,是fb面经= =……那个人人品也是可以

和remove duplicates from sorted array道理是一样的,用i对整个数组走一遍,然后用index保持有效的位置。最后把index及之后的都填成0就可以了

代码

public void moveZeroes(int[] nums) {
    if(nums.length == 0) {
        return;
    }
    int index = 0;
    int n = nums.length;
    for(int i = 0; i < n; i++) {
        if(nums[i] != 0) {
            nums[index++] = nums[i];
        }
    }
    for(int i = index; i < n; i++) {
        nums[i] = 0;
    }
}

results matching ""

    No results matching ""