75.颜色分类
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
使用一遍排序法来做,本质是快排
三个指针,分别指向第一个非0元素,当前下标,第一个非2元素
class Solution {
void swap(int[]num, int a, int b){
int temp = 0;
temp = num[a];
num[a] = num[b];
num[b] = temp;
}
public void sortColors(int[] nums) {
int left = 0, right = nums.length - 1, cur = 0;
while(cur <= right){
if(nums[cur] == 0){
swap(nums, cur ++, left ++);
}
else if(nums[cur] == 2){
swap(nums, cur, right --);
//注意,此时的cur不前移!!!因为交换完之后,cur的位置出现了新的未处理的值,这个算法的关键是cur会遍历整个数组进行判断!!!
}
else if(nums[cur] == 1){
cur ++ ;
}
}
}
}