JAVA O(N) SOLUTION - 10 LINES


  • 0

    Two pointer solution; insert pointer serves as the location which will be updated next. scanner pointer searches for next appropriate value to insert at insert pointer. Once scanner pointer reaches the end all unevaluated indices after insert are set to 0.

    In the worst case scenario the array is essentially looped through twice if the only non zero value is the vary last index. However this solution is still O(n) in time, and O(1) with space.

         public void moveZeroes(int[] nums) {
            int insert = 0, scanner = 0;
            while(insert < nums.length){
                if(scanner == nums.length){
                    nums[insert] = 0;
                    insert++;
                }else if(nums[scanner] != 0){
                    nums[insert] = nums[scanner];
                    insert++;
                    scanner++;
                }else scanner++;
            }
        }

Log in to reply
 

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