75. Sort Colors

August 15, 2016

75.Sort Colors

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: You are not suppose to use the library’s sort function for this problem.

Follow up: A rather straight forward solution is a two-pass algorithm using counting sort.

First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.

Could you come up with an one-pass algorithm using only constant space?

/*solution1 4ms use counting sort*/
class Solution {
public:
void sortColors(vector<int>& nums) {
int i=0,j=0,k=0;
vector<int> zero;
vector<int> one;
vector<int> two;
for(i=0;i<nums.size();i++){
switch(nums[i]){
case 0:
zero.push_back(nums[i]);
break;
case 1:
one.push_back(nums[i]);
break;
case 2:
two.push_back(nums[i]);
break;
}
}
for(i=0;i<zero.size();i++)
nums[i]=zero[i];
for(i,j=0;j<one.size();i++,j++)
nums[i]=one[j];
for(i,k=0;k<two.size();i++,k++)
nums[i]=two[k];
}
};


1. nums[cur]==0 应该将其与low指向的元素交换，因为nums[low]始终 ==1或low ==cur,所以交换后的nums[cur]已经到位,只需cur++，low++
2. nums[cur]==1 已经就位，cur++即可
3. nums[cur]==2 应该将其与high指向的元素作交换，但是high指向的元素的值不确定，所以只能让high–，cur不变

1 0 2 2 1 0
^         ^
L         H
M

Mid != 0 || 2
Mid++

1 0 2 2 1 0
^ ^       ^
L M       H

Mid == 0
Swap Low and Mid
Mid++
Low++

0 1 2 2 1 0
^ ^     ^
L M     H

Mid == 2
Swap High and Mid
High--

0 1 0 2 1 2
^ ^   ^
L M   H

Mid == 0
Swap Low and Mid
Mid++
Low++

0 0 1 2 1 2
^ ^ ^
L M H

Mid == 2
Swap High and Mid
High--

0 0 1 1 2 2
^ ^
L M
H



class Solution {
public:
void sortColors(vector<int>& nums) {
int low=0,high=nums.size()-1,cur=0;
while(cur<=high){
if(nums[cur]==0)
swap(nums[cur++],nums[low++]);
else if(nums[cur]==1)
cur++;
else if(nums[cur]==2)
swap(nums[cur],nums[high--]);
}
}
};


学籍管理系统文档

北邮教务系统评教脚本

Published on September 17, 2017

72.Edit distance

Published on September 17, 2017