Tuesday, June 17, 2014

Sort Colors -- Leetcode

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.
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;
}
  1. class Solution {  
  2. public:  
  3.     void sortColors(int A[], int n) {  
  4.         int red = 0, blue = n - 1;  
  5.           
  6.         for(int i = 0; i < blue + 1; )  
  7.         {  
  8.             if(A[i] == 0)  
  9.                 swap(A[i++], A[red++]);  
  10.             else if(A[i] == 2)  
  11.                 swap(A[i], A[blue--]);  
  12.             else  
  13.                 i++;  
  14.         }  
  15.     }  
  16. };  

No comments:

Post a Comment