Java one pass code


  • 0
    B

    public class Solution {

     public void sortColors(int[] nums) {
        if(nums == null) return ;
        int zero = 0, second = nums.length - 1;
        int cur = 0;
        while(cur <= second) {
            if(nums[cur] == 0) {
                swap(nums, cur++, zero++);
            } else if(nums[cur] == 1) {
                cur++;
            } else if(nums[cur] == 2) {
                swap(nums, cur, second--);
            }
        }
    }
    
    private void swap(int []nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
    

    }


Log in to reply
 

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