Java solution of Move Zeroes


  • 18
    V

    public class Solution {

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

    }


  • 0
    R

    I really like this one, easy to understand, and fast with O(n)


  • 1
    A

    This is my solution. It's linear time, with O(1) space.
    If it is not the best solution can you tell me why?

    int i = 0;
    int j = 0;
    while (j < nums.length){
        if (nums[j] != 0){
            int tmp = nums[j];
            nums[j] = nums[i];
            nums[i] = tmp;
            i++;
        }
        j++;
    }

  • 0

    @vy7Sun Your code is easy to understand. The corner case if (nums == null) is not necessary.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.