My Java code, using 1 pointer


  • 0
    J

    At first my idea was to locate the first 0, and then swap with the first non-0 after 0s. But I found a little bit hard to fix this 0 location.

    Now my algorithm is to go through the array from beginning, when there is a 0, skip; if not 0, then swap with the first 0 that from previous sub-array (same logic but different pointer).

    Code as follow, not know about efficiency.

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

    Please correct or help improve. Thanks a lot.


  • 0
    H

    This is actually not 1 pointer. You have "curr" and "i" two pointers


Log in to reply
 

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