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

分类:Array Two Pointers Sort

代码:

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

 

posted @ 2016-08-12 18:57  zhangbaochong  阅读(170)  评论(0)    收藏  举报