1. 快排
class Solution {
public void sortColors(int[] nums) {
quickSort(nums,0,nums.length-1);
}
//快排
public void quickSort(int[] nums,int start,int end){
if(start < end){
int pivot = getPivot(nums,start,end);
quickSort(nums,start,pivot-1);
quickSort(nums,start+1,end);
}
}
//返回pivot
public int getPivot(int[] nums,int start,int end){
int num = nums[start];
while(start < end){
while(start < end && nums[end] >= num)
end--;
nums[start] = nums[end];
while(start < end && nums[start] <= num)
start++;
nums[end] = nums[start];
}
nums[start] = num;
return start;
}
}
2. 双指针将0放到前面,2放到后面
class Solution {
public void sortColors(int[] nums) {
int p0 = 0,p2 = nums.length-1,i = 0;
while(i < nums.length){
if(nums[i] == 0 && i > p0)
swap(nums,p0++,i);
else if(nums[i] == 2 && i < p2)
swap(nums,p2--,i);
else
i++;
}
}
public void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}