题目描述:

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?

解题思路:

我一开始的思路是遍历数组,把0放在前面,然后把1放在0的后面,只需遍历一次。

后来看了优质解答,根据他人的思路我将代码调整了下,把0放在前面,2放在后面。

First Code:

 1 class Solution {
 2 public:
 3     void sortColors(vector<int>& nums) {
 4         int index = 0, n = nums.size();
 5         for(int i = 0; i < n; i++){
 6             if(nums[i] == 0 && i != index){
 7                 nums[index]^=nums[i];
 8                 nums[i]^=nums[index];
 9                 nums[index++]^=nums[i];
10             }
11             if(nums[i] == 0 && i == index)
12                 index++;
13         }
14         for(int i = index; i < n; i++){
15             if(nums[i] == 1 && i != index){
16                 nums[index]^=nums[i];
17                 nums[i]^=nums[index];
18                 nums[index++]^=nums[i];
19             }
20             if(nums[i] == 1 && i == index)
21                 index++;
22         }
23     }
24 };

Second Code:

 1 class Solution {
 2 public:
 3     void sortColors(vector<int>& nums) {
 4         int left = 0, right = nums.size() - 1, i = 0;
 5         while(i <= right){
 6             if(nums[i] == 0){
 7                 if(i == left){
 8                     i++;
 9                     left++;
10                 }
11                 else{
12                     nums[i] ^= nums[left];
13                     nums[left] ^= nums[i];
14                     nums[i++] ^= nums[left++];
15                 }
16             }
17             else if(nums[i] == 2){
18                 if(i == right)
19                     right--;
20                 else{
21                     nums[i] ^= nums[right];
22                     nums[right] ^= nums[i];
23                     nums[i] ^= nums[right--];
24                 }
25             }
26             else
27                 i++;
28         }
29     }
30 };

 

 

 

 
posted on 2018-03-12 13:08  宵夜在哪  阅读(99)  评论(0编辑  收藏  举报