75.颜色分类

2020/10/1
class Solution {
    public void sortColors(int[] nums) {
        int r=0, w=0, length=nums.length;
        for(int i=0;i<length;i++){
            if(nums[i]==1){
            //    int temp = nums[i];
                nums[i] = nums[w];
                nums[w] = 1;
                w++;
            }else if(nums[i]==0){
                // int temp = nums[i];
                nums[i] = nums[r];
                nums[r] = 0;
                if(r<w){
                    int temp = nums[i];
                    nums[i] = nums[w];
                    nums[w] = temp;
                }
                r++;
                w++;//无论为0还是1,w都得后移一位
            }
        }                                      
    }
}

Last Updated: 4/4/2024