[leetcode.com]算法题目 - 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.

click to show follow up.

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?

 class Solution {
public:
void swap(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
void sortColors(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (n<) return; int first = ;
int last = n-;
while(first<n && ==A[first])
first++;
while(last>= && ==A[last])
last--; int i=first;
while(first < last && i<=last){
if (==A[i]){
swap(A[i],A[last]);
last--;
while(last>= && ==A[last])
last--;
}else if(==A[i]){
swap(A[i],A[first]);
first++;
if(i<first) i=first;
while(first<n && ==A[first])
first++;
}else{
i++;
}
}
}
};

我的答案

思路:如果只需要一次遍历,就地排序,其实在循环到每个数的时候要比两次遍历多做一些事情。因为0肯定是排在前面的,2肯定是排在后面的,指定两个指针,分别指向数组的两头,然后往中间缩进,注意分别讨论遍历到0,1,2时应该做何种运算,何种操作即可。

上一篇:chrome web开发工具


下一篇:tomcat nio apr