参考资料:左程云算法课
75. Sort Colors
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
思路:荷兰国旗问题,快速排序的partition函数。
把数组分为<1Area, =1Area, >1Area等三个区;
<1Area 的右边界(闭的)用less表示,
>1Area
的左边界(闭的)用more表示,
cur是用于遍历数组的指针,
如果他所指的元素大于1,那么 把当前元素发货到>1Area
的最新左边界位置(相当于向左扩展左边界), and cur++;
如果他所指的元素小于1,那么 把当前元素发货到<1Area` 的最新右边界位置(相当于向右扩展右边界), and cur++;
如果他所指的元素等于1,那么 把他留在这,that is =Area, and cur++,
class Solution {
public void sortColors(int[] nums) {
int n = nums.length;
// <1 =1, >1
int less=-1;
int more = n;
int cur=0;
// nums[cur], <1 less++,cur++, ==1 cur++, >1 swap(nums,cur,--more)
while(cur<more)
{
if(nums[cur]<1)
{
swap(nums,cur++,++less);
}else if(nums[cur]==1)
{
//swap(nums,cur++,1+less);
cur++;
}else{
swap(nums,cur,--more);
}
}// end while
}
public void swap(int[] nums, int i, int j)
{
int t= nums[i];
nums[i] = nums[j];
nums[j]=t;
}
}