Java solution 1ms two pointers


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

    }


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

    }


  • 0

    move all none zero element to front, then set others to 0


Log in to reply
 

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