Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

75. Sort Colors #165

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

public class Solution { public void sortColors(int[] nums) { int p1 = 0, p2 = nums.length - 1, index = 0; while(index <= p2) { if(nums[index] == 0) { nums[index] = nums[p1]; nums[p1] = 0; p1++; } if(nums[index] == 2) { nums[index] = nums[p2]; nums[p2] = 2; p2--; index--;//此处index减去1是因为,p2和index位置交换后,index位置上的元素属性未知,要重新判断index位置的元素 } index++; }

    /*
    //two pass
    int count0 = 0, count1 = 0, count2 = 0;
    for(int i = 0; i < nums.length; i++) {
        if(nums[i] == 0) count0++;
        if(nums[i] == 1) count1++;
        if(nums[i] == 2) count2++;
    }
    for(int j = 0; j < nums.length; j++) {
        if(j < count0) {
            nums[j] = 0;
        } else if(j < count0 + count1) {
            nums[j] = 1;
        } else {
            nums[j] = 2;
        }
    }
    */
}

}

Shawngbk commented 7 years ago

pocketgem