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.

Analyse: First put all 0s in the left parts, then put all 2s in the right parts.

Runtime: 4ms.

new version!!

 1 class Solution {
 2 public:
 3     void sortColors(vector<int>& nums) {
 4         if(nums.size() <= 1) return;
 5         
 6         int red = 0, blue = nums.size() - 1;
 7         for(int i = 0; i < blue + 1; ){
 8             if(nums[i] == 0){
 9                 swap(nums[i], nums[red]);
10                 red++;
11                 i++;
12             }
13             else if(nums[i] == 2){
14                 swap(nums[i], nums[blue]);  //be careful about this index!!
15                 blue--;
16             }
17             else i++;
18         }
19         
20         return;
21     }
22 };
 1 class Solution {
 2 public:
 3     void sortColors(vector<int>& nums) {
 4         if(nums.size() <= 1) return;
 5         
 6         int index = 0;
 7         
 8         //sort all 0s in the left part
 9         for(int i = 0; i < nums.size(); i++){
10             if(nums[i] == 0){
11                 swap(nums[index], nums[i]);
12                 index++;
13             }
14         }
15         
16         //sort all 2s int the right part
17         if(index < nums.size()){
18             int move = nums.size() - 1;
19             for(int j = move; j >= index; j--){
20                 if(nums[j] == 2){
21                     swap(nums[j], nums[move]);
22                     move--;
23                 }
24             }
25         }
26         
27         return;
28     }
29 };
原文地址:https://www.cnblogs.com/amazingzoe/p/4669998.html