Question:
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.
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?
Answer:
分析:根据题目示意,可以使用计数排序方法得到最后的结果。但是计数排序使用的是两趟遍历,若要达到一趟遍历的效果,可以考虑设置两个标记位,分别用来记录0、2两种颜色,然后依次从前或从后进行替换。
o(n) time, o(1) space. In place method.
My code:
void sortcolors(int a[], int n){int red = 0, i=0, blue=n-1;
while (i <= blue){
if(a[i] == 0){
std::swap(a[i],a[red]);
i++;
red++;
}
else if(a[i]==2){
std::swap(a[i],a[blue]);
blue--;
}
else if(a[i] ==1){
i++;
}
}
}
int main(){
int a[] ={2,1,1,0,1,2,2,0,0,0,2,2,1,2,0,2};
int len = sizeof(a)/sizeof(int);
sortcolors(a,len);
for(int i=0;i<len;++i){
std::cout<< a[i] << ' ';
}
getchar();
return 0;
}
- class Solution {
- public:
- void sortColors(int A[], int n) {
- int red = 0, blue = n - 1;
- for(int i = 0; i < blue + 1; )
- {
- if(A[i] == 0)
- swap(A[i++], A[red++]);
- else if(A[i] == 2)
- swap(A[i], A[blue--]);
- else
- i++;
- }
- }
- };
No comments:
Post a Comment