标签:style blog http io ar color os sp for
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?
Array Two Pointers Sort
3.中zeroidx 可以一直+1 不直接跳位,这样需要多次交换,discuss 实现多是这样。
下面是我写的代码:
1 #include <iostream> 2 using namespace std; 3 4 class Solution { 5 public: 6 void sortColors(int A[], int n) { 7 int zeroIdx = 0; 8 int twoIdx = n; 9 for(int i =0;i<n&&i<twoIdx;i++){ 10 if(A[i]==1){ 11 continue; 12 } 13 if(A[i]==0){ 14 A[i] = A[zeroIdx]; 15 A[zeroIdx] = 0; 16 if(++zeroIdx<n&&A[zeroIdx]==0) zeroIdx=i+1; 17 } 18 else if(A[i]==2){ 19 twoIdx--; 20 A[i]=A[twoIdx]; 21 A[twoIdx]=2; 22 i--; 23 } 24 else 25 return ; 26 } 27 return ; 28 } 29 }; 30 31 int main() 32 { 33 int a[] = {1,2,0,1}; 34 Solution sol; 35 sol.sortColors(a,sizeof(a)/sizeof(int)); 36 for(int i=0;i<sizeof(a)/sizeof(int);i++) 37 cout<<a[i]<<" "; 38 cout<<endl; 39 return 0; 40 }
discuss 中有一个实现非常不错,逻辑清晰,可以将变量数3 扩展为k 个,只要不怕写起来麻烦,其逻辑类似于插入排序,将遍历的项插入正确的位置:
1 public void sortColors(int[] A) { 2 3 4 int i=-1, j=-1, k=-1; 5 6 for(int p = 0; p < A.length; p++) 7 { 8 if(A[p] == 0) 9 { 10 A[++k]=2; 11 A[++j]=1; 12 A[++i]=0; 13 } 14 else if (A[p] == 1) 15 { 16 A[++k]=2; 17 A[++j]=1; 18 19 } 20 else if (A[p] == 2) 21 { 22 A[++k]=2; 23 } 24 } 25 26 }
[LeetCode] Sort Colors 只有3个类型的排序
标签:style blog http io ar color os sp for
原文地址:http://www.cnblogs.com/Azhu/p/4129351.html