Java solution, one pass


  • 0
    C
    public class Solution {
        public void sortColors(int[] nums) {
            if(nums == null || nums.length == 0){
                return;
            }
            int lo=0,redEnd=-1,hi=nums.length-1;
            while(lo <= hi){
                if(nums[lo] == 0){
                    if(lo == redEnd +1){
                        lo++;
                        redEnd++;
                    }else{
                        int tem = nums[redEnd+1];
                        nums[redEnd+1] = nums[lo];
                        nums[lo] = tem;
                        redEnd++;
                        lo++;
                    }
                }else if(nums[lo] == 2){
                    while(lo <= hi && nums[hi] == 2){
                        hi--;
                    }
                    if(lo > hi){
                        break;
                    }
                    int tem = nums[hi];
                    nums[hi] = nums[lo];
                    nums[lo] = tem;
                }else{
                    lo++;
                }
                
            }
        }
    }
    

Log in to reply
 

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