zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    Note:
    You are not suppose to use the library's sort function for this problem.

    荷兰国旗问题。

    1.问题描述:

    我们将乱序的红白蓝三色小球排列成有序的红白蓝三色的同颜色在一起的小球组。这个问题之所以叫荷兰国旗,是因为我们可以将红白蓝三色小球想象成条状物,有序排列后正好组成荷兰国旗。

    2.问题分析:

    这个问题我们可以将这个问题视为一个数组排序问题,这个数组分为前部,中部和后部三个部分,每一个元素(红白蓝分别对应0、1、2)必属于其中之一。由于红、白、蓝三色小球数量并不一定相同,所以这个三个区域不一定是等分的,也就是说如果我们将整个区域放在[0,1]的区域里,由于三色小球之间数量的比不同(此处假设1:2:2),可能前部为[0,0.2),中部为[0.2,0.6),后部为[0.6,1]。我们的思路如下:将前部和后部各排在数组的前边和后边,中部自然就排好了。具体的:

    设置两个标志位begin和end分别指向这个数组的开始和末尾,然后用一个标志位current从头开始进行遍历:

    1)若遍历到的位置为0,则说明它一定属于前部,于是就和begin位置进行交换,然后current向前进,begin也向前进(表示前边的已经都排好了)。

    2)若遍历到的位置为1,则说明它一定属于中部,根据总思路,中部的我们都不动,然后current向前进。

    3)若遍历到的位置为2,则说明它一定属于后部,于是就和end位置进行交换,由于交换完毕后current指向的可能是属于前部的,若此时current前进则会导致该位置不能被交换到前部,所以此时current不前进。而同1),end向后退1。

    以上原文:http://www.cnblogs.com/sharpfeng/archive/2012/09/05/2671630.html

     1 class Solution {
     2 public:
     3     void sortColors(int A[], int n) {
     4         int begin = 0, end = n - 1, cur = 0, tmp;
     5         while (cur <= end) {
     6             if (A[cur] == 0) {
     7                 tmp = A[cur];
     8                 A[cur++] = A[begin];
     9                 A[begin++] = tmp;
    10             } else if (A[cur] == 2) {
    11                 tmp = A[cur];
    12                 A[cur] = A[end];
    13                 A[end--] = tmp;
    14             } else {
    15                 ++cur;
    16             }
    17         }
    18     }
    19 };

    因为只有0、1、2,可以直接统计0、1、2的数量,然后挨个放到数组里,同样是O(n)的复杂度,但是要遍历两遍数组。

     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             if (A[i] == 0) ++red;
     7             if (A[i] == 1) ++white;
     8             if (A[i] == 2) ++blue;
     9         }
    10         int idx = 0;
    11         while (red--) A[idx++] = 0;
    12         while (white--) A[idx++] = 1;
    13         while (blue--) A[idx++] = 2;
    14     }
    15 };
  • 相关阅读:
    luogu1196 银河英雄传说 (并查集)
    [BZOJ2243][SDOI2011]染色
    [BZOJ1879] [Sdoi2009]Bill的挑战
    [Noip2003] 侦探推理
    [Noip2005] 篝火晚会
    [JZOJ100047] 【NOIP2017提高A组模拟7.14】基因变异
    [九省联考2018]一双木棋chess
    [Noip2009] 靶形数独
    [Luogu2737] [USACO4.1]麦香牛块Beef McNuggets
    [BZOJ3109] [cqoi2013]新数独
  • 原文地址:https://www.cnblogs.com/easonliu/p/4384274.html
Copyright © 2011-2022 走看看