leetcode75 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.

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 sortColors(vector<int>& nums) {
 4 
 5         int size=nums.size();
 6         vector<int> c_list(3,0);
 7         for(int i=0;i<size;i++)
 8         {
 9             c_list[nums[i]]++;
10         }
11         int i=0;
12         while(c_list[0]>0)
13         {
14             nums[i]=0;
15             c_list[0]--;
16             i++;
17         }
18         while(c_list[1]>0)
19         {
20             nums[i]=1;
21             c_list[1]--;
22             i++;
23         }
24         while(c_list[2]>0)
25         {
26             nums[i]=2;
27             c_list[2]--;
28             i++;
29         }
30         
31     }
32 };
View Code

 

posted @ 2016-01-06 15:56  西小贝  阅读(108)  评论(0编辑  收藏  举报