JAVA O(n) no extra space


  • 0
    O
    public static void moveZeroes(int[] nums) {
            int len = nums.length;
            if(len == 0)
                return;
            int i = 0;
            int j = 0;
            while(i < len && nums[i] == 0){
                i++;
            }
            while(j < len && nums[j] != 0){
                j++;
            }
            while(i < len && j < len){
                if(i > j) { // zero element appears before non zero element
                    int tmp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = tmp;
                    i++;
                    j++;
                    while(i < len && nums[i] == 0){
                        i++;
                    }
                    while(j < len && nums[j] != 0){
                        j++;
                    }
                }else{ // zero element appears after non zero element
                    i++;
                    while(i < len && nums[i] == 0){
                        i++;
                    }
                }
            }
            return;
        }
    

Log in to reply
 

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