clean, explained Java Code, one pass


  • 0
    D
    public class Solution {
        public void sortColors(int[] nums) {
            int lo = 0;
            int hi = nums.length - 1;
            
            // two pointer, swap 0 to lo, and 2 to hi
            
            for(int i = 0;i<nums.length && i<=hi;i++){
                if(nums[i] == 1) continue;
                if(nums[i] == 0){
                    swap(nums,i,lo);    // the new swapped val must be 0 or 1, not need continue at this index
                    lo++;
                }else{
                    swap(nums,i,hi);
                    hi--;
                    i--;    //the new swapped in val can be 0,1,2, need continue at this index
                }
            }
        }
        
        public void swap(int [] nums,int i, int j){
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }
    

Log in to reply
 

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