码迷,mamicode.com
首页 > 编程语言 > 详细

[Leetcode] sort colors 颜色排序

时间:2017-07-01 17:16:29      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:represent   赋值   arch   中间   cti   ble   函数   this   not   

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?

 题意:数组内有n个0,1,2,进行排序,使其按照0,1,2的顺序,即,红,白,蓝的顺序。
思路:方法一:因为这里是用0,1,2来代表红、白、蓝,其是按阿拉伯数字的大小顺序,所以可以直接用sort函数(sort(A,A+n)),解决问题。题目不准。方法二:可以通过三个计数器,分别记录下0,1,2的个数,然后将数组重新赋值即可;方法三:这就是荷兰国旗的问题(详见gnuphc)。将数组分为三部分,前部(全是0)、中部(全是1)、后部(全是2)三个部分,这样数组中的每个元素就必属于其中之一,那将前部、后部排列好了,中间就自然排列好了。定义两个指针:beg、end,beg开始指向第一个元素,end指向最后一个元素,然后用指针cur遍历数组,根据总的思路,中部我们不动。情况如下:
  1)若遍历到值为1的元素,则说明其属于中部,中部的不动,cur向后移动一个位置;
  2)若是遇到值为0的元素,则说明其必属于前部,于是和beg的位置的值进行交换,然后cur向后移动一个位置,beg也向后移动一个位置,表示beg之前的部分已经排好了。
  3)若是遇到值为2的元素,则说明其必属于后部,于是,和end位置的值进行交换,然后end向前移动一个位置,表示end之后的都排好了,但是,cur不要向后移动一个位置,因为交换后的cur所指向的值是否等于0 ,即属于前部还没有比较,所以,下次循环还是从此处开始。
代码如下:
 1 class Solution {
 2 public:
 3     void sortColors(int A[], int n) 
 4     {
 5         int beg=0;
 6         int end=n-1;
 7         int cur=0;
 8 
 9         while(cur<=end)
10         {
11             if(A[cur]==0)
12             {
13                 swap(A[cur],A[beg]);
14                 cur++;
15                 beg++;
16             }
17             else if(A[cur]==1)
18             {
19                 cur++;
20             }
21             else
22             {
23                 swap(A[cur],A[end]);
24                 end--;
25             }
26         }    
27     }
28 };

 

[Leetcode] sort colors 颜色排序

标签:represent   赋值   arch   中间   cti   ble   函数   this   not   

原文地址:http://www.cnblogs.com/love-yh/p/7102738.html

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