Medium
counting sort的方法不说了,比较简单,直接上partition那个方法, 用two pointers. 把0全部赶到左边,2赶到右边,要注意每次变化之后指针怎么变: left, right, i都分别怎么变
class Solution {
public void sortColors(int[] nums) {
int left = 0;
int right = nums.length - 1;
int i = 0;
while (i <= right){
if (nums[i] == 0){
swap(nums, i, left);
left++;
i++;
} else if (nums[i] == 2){
swap(nums, i, right);
right--;
} else {
i++;
}
}
}
private void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}