Simple O(n) solution in Java


  • 0
    W
    public class Solution {
    public void moveZeroes(int[] nums) {
        int length = nums.length;
        if (length == 1) {
            return;
        }
        int p1 = 0;
        int p2 = 0;
        while (p2 < length) {
            while (p2 < length && nums[p2] == 0) {
                p2 ++;
            }
            while (p1 < p2 && nums[p1] != 0) {
                p1 ++;
            }
            if (p2 < length) {
                int tmp = nums[p1];
                nums[p1] = nums[p2];
                nums[p2] = tmp;  
                p2 ++;
                p1 ++;
            }
        }
    }
    

    }


Log in to reply
 

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