码迷,mamicode.com
首页 > 其他好文 > 详细

Sort Colors

时间:2015-07-23 11:56:52      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

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.

 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 };

 

Sort Colors

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4669998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!