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 e.g., 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.

public class Solution {
    public void moveZeroes(int[] nums) {
        for (int i = 0; i < nums.length-1; i++) {
            if (nums[i] == 0) {
                int next_nonezero_index = check_index(nums, i);
                if (next_nonezero_index == -1) {
                    break; 
                } else {
                    nums[i] = nums[next_nonezero_index];
                    nums[next_nonezero_index] = 0; 
                }
            }
        }
    }
    
    
    
    public int check_index (int[] nums, int cur) {
        int index = 0; 
        for (int i = cur+1; i < nums.length; i++) {
            if (nums[i] != 0) {
                index = i; 
                break; 
            } 
            if (nums[i] == 0 && i == (nums.length -1) ) {
                index = -1;
            }
        }
        
        return index; 
    }
}

Simpler Version:

public void moveZeroes(int[] nums) {
        int nextPos = 0;
        for(int i = 0; i < nums.length; i++){
            if(nums[i] != 0){
                nums[nextPos] = nums[i];
                if(i != nextPos)
                    nums[i] = 0;
                nextPos++;
            }
        }
}
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