LeetCode 75. 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?


 
 

题目看上去不难,但是还有有很多陷阱,其实只需要调用sort()函数就可以解决问题,但是题目明确说不行;简单粗暴的办法是分别统计0,1,2的数量,然后重新对向量赋值,代码如下:

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

但是这么做需要遍历两遍向量,那么我们不妨换个思路,用一头一尾两个指针p1,p2分别表示0的结束为止和2的起始位置,然后逐一遍历数组,遇见0和p1位置的元素交换,遇见2和p2未知的元素交换。这里有个地方其实值得思考,就是什么情况下需要考虑index的增加,什么情况下不需要考虑。具体需要注意的地方写在了以下代码的注释中

易错点:while条件中为<=,index在遍历到2时不可改变!

 1 class Solution {
 2 public:
 3     void sortColors(vector<int>& nums) {
 4         int p1 = 0, p2 = nums.size() - 1, index = 0;
 5         while (index <= p2)
 6         {
 7             if (nums[index] == 0)
 8             {
 9                 //swap(nums[index], nums[p1]);
10                 //当然也可以自己写交换的部分
11                 nums[index] = nums[p1];
12                 nums[p1] = 0;
13                 index++;
14                 p1++;
15             }
16             else if (nums[index] == 2)
17             {
18                 //这样写相对于交换,可以简单一些
19                 nums[index] = nums[p2];
20                 nums[p2] = 2;
21                 //index++;    //这里不要改变index,因为交换之后此处如果为0  还需要继续交换
22                 p2--;
23             }
24             else
25                 index++;
26         }
27     }
28 };

 

posted @ 2018-01-24 16:24  皇家大鹏鹏  阅读(174)  评论(0编辑  收藏  举报