## [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.

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?

 1 class Solution {
2 public:
3     void swap(int &a, int &b){
4         int temp = a;
5         a = b;
6         b = temp;
7     }
8     void sortColors(int A[], int n) {
9         // Start typing your C/C++ solution below
10         // DO NOT write int main() function
11         if (n<2) return;
12
13         int first = 0;
14         int last = n-1;
15         while(first<n && 0==A[first])
16             first++;
17         while(last>=0 && 2==A[last])
18             last--;
19
20         int i=first;
21         while(first < last && i<=last){
22             if (2==A[i]){
23                 swap(A[i],A[last]);
24                 last--;
25                 while(last>=0 && 2==A[last])
26                     last--;
27             }else if(0==A[i]){
28                 swap(A[i],A[first]);
29                 first++;
30                 if(i<first) i=first;
31                 while(first<n && 0==A[first])
32                     first++;
33             }else{
34                 i++;
35             }
36         }
37     }
38 };

posted on 2013-09-24 21:32  Horstxu  阅读(390)  评论(0编辑  收藏  举报