首页 > 其他 > 详细

Sort Colors

时间:2015-07-23 11:54:40      阅读:117      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!