Java: one pass with two reverse operations


  • 0
    R

    My below code passed OJ by doing two reverse operations between the two pointers: i, j. It's not the simplest, but I would just like to provide an alternative solution :)

    public void moveZeroes(int[] nums) {
            
            int i = 0, j = nums.length - 1;
            
            while (i < j && j >= 0 && i < nums.length) {
                
                while (i < j && i < nums.length && nums[i] != 0) { i++; }
                while (i < j && j >= 0 && nums[j] == 0) { j--; }
                
                if (nums[i] == 0 && nums[j] != 0) {
                    reverse(nums, i, j);
                    j--;
                    reverse(nums, i, j);
                }
            }
    
    private static void reverse(int[] A, int lo, int hi) {
            int mid = lo + (hi - lo) / 2;
            while (lo <= mid) {
                int temp = A[lo];
                A[lo++] = A[hi];
                A[hi--] = temp;
            }
        }
    
    
    

Log in to reply
 

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