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

Leetcode | Sort Colors

时间:2014-05-07 18:01:05      阅读:412      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   color   

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?

如提示,最简单的就是扫描两遍,第一遍计数,第二遍填数。

32ms

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     void sortColors(int A[], int n) {
 4         int red = 0, white = 0, blue = 0; 
 5         for (int i = 0; i < n; ++i) {
 6             switch(A[i]) {
 7                 case 0: red++; break;
 8                 case 1: white++; break;
 9                 case 2: blue++; break;
10             }
11         }
12         
13         for (int i = 0; i < red; ++i) A[i] = 0;
14         for (int i = 0; i < white; ++i) A[red + i] = 1;
15         for (int i = 0; i < blue; ++i) A[red + white + i] = 2;
16     }
17 };
bubuko.com,布布扣

一遍的没想清楚,看完网上的思路再重写了一遍。我的理解是这样:

双指针,red 记录已经放在正确位置的0的个数,blue记录已经放在正确位置的2的个数。同时用i从头扫描到blue。

1. 当碰到0时,放到A[red]这个位置上,red需要累加,i也需要累加。red累加很好理解,i累加是因为red必然<=i, 当A[i]=0时,和A[red]交换之后,要想在A[red+1...i]之间再找到0已经不可能了,因为0值都被交换到red前面了,所以要想再找到0值只能i++。

2. 当i到达blue的位置的时候,因为A[blue+1...n-1]都是2,所以已经不用再继续了。可以退出。

3. 注意blue这个位置还没有填充2,所以i是可以,也必须走到blue的。

8ms

bubuko.com,布布扣
class Solution {
public:
    void sortColors(int A[], int n) {
        int i = 0;
        int red = 0, blue = n - 1;
        while (i <= blue) {
            if (A[i] == 0) {
                swap(A[i], A[red]);
                red++;
                i++;
            } else if (A[i] == 2) {
                swap(A[i], A[blue]);
                blue--;
            } else {
                i++;
            }
        }
    }
};
bubuko.com,布布扣

 

Leetcode | Sort Colors,布布扣,bubuko.com

Leetcode | Sort Colors

标签:style   blog   class   code   java   color   

原文地址:http://www.cnblogs.com/linyx/p/3709940.html

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