很重要的一道题,考察的是快排的partition思路。
1、先写了个快排练手,果然很久没写了。。有好几个BUG。。。
1 class Solution { 2 public: 3 int partition(int objects[], int start, int end) { 4 int pivot = objects[start]; 5 while (start < end) { 6 while (start < end && objects[end] >= pivot) {end--;} 7 if (start < end) { 8 objects[start] = objects[end]; 9 } 10 while (start < end && objects[start] <= pivot) {start++;} 11 if (start < end) { 12 objects[end] = objects[start]; 13 } 14 } 15 objects[start] = pivot; 16 return start; 17 } 18 void quickSort(int objects[], int start, int end) { 19 if (start >= end) return; 20 int pivot = partition(objects, start, end); 21 quickSort(objects, start, pivot - 1); 22 quickSort(objects, pivot + 1, end); 23 } 24 void sortColors(int A[], int n) { 25 quickSort(A, 0, n - 1); 26 } 27 };
快排的时间复杂度是O(n*lgn),空间复杂度是O(1)
2、更简单的是记录一下0,1,2的个数。。。就像题目里所说的一样。。
关键是如何想出来一种one-pass的方法,只需要遍历一次即可!其实每个元素还是访问了好多次。
1 class Solution { 2 public: 3 void sortColors(int A[], int n) { 4 int left = 0; 5 int right = n - 1; 6 int i = 0; 7 while(i <= right) { 8 if (A[i] == 0 && i != left) { 9 swap(A[left++], A[i]); 10 } else if (A[i] == 2 && i != right) { 11 swap(A[right--], A[i]); 12 } else { 13 i++; 14 } 15 } 16 } 17 };
代码很简单,边界想了很多次,忧桑~
3、用Paritition做,可以扩展到n种颜色。
看到了一篇文章http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Flag/ ,说的挺清楚的。于是模仿着又写了一遍。
其实本质是一样的,用2个指针来标记范围,一个指针不停的往后移动。
其实不太确定怎么用。需要进一步深入研究!!