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.

思路: 两个指针来做, 一个index用来存非0的数,另一个指针i用来遍历. for循环当nums[i] != 0,则nums[index]保存此数。 最后把从index到nums.length之间的数填0

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

    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s