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.
    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?
    » Solve this problem

    [解题思路]
    一开始想到的就是计数排序,但是计数排序需要两边扫描,第一遍统计红,白,蓝的数目,第二遍生成新数组。

    考虑到题目要求one pass。这就意味着类似于链表的双指针问题,这里也要track两个index,一个是red的index,一个是blue的index,两边往中间走。

    i从0到blue index扫描,
    遇到0,放在red index位置,red index后移;
    遇到2,放在blue index位置,blue index前移;
    遇到1,i后移。
    扫描一遍得到排好序的数组。时间O(n),空间O(1),

    [Code]
    two-pass solution, Counting sort solution
    1:       void sortColors(int A[], int n) {   
    2: // Start typing your C/C++ solution below
    3: // DO NOT write int main() function
    4: int red=0, white =0, blue=0;
    5: for(int i =0; i < n; i++)
    6: {
    7: switch(A[i])
    8: {
    9: case 0:
    10: red++;break;
    11: case 1:
    12: white++;break;
    13: case 2:
    14: blue++;break;
    15: }
    16: }
    17: for(int i =0; i<n; i++)
    18: {
    19: if(red>0)
    20: {
    21: A[i]=0;
    22: red--;
    23: continue;
    24: }
    25: if(white>0)
    26: {
    27: A[i] =1;
    28: white--;
    29: continue;
    30: }
    31: A[i]=2;
    32: }
    33: }


    one-pass, two pointers solution
    1:       void sortColors(int A[], int n) {   
    2: // Start typing your C/C++ solution below
    3: // DO NOT write int main() function
    4: int redSt=0, bluSt=n-1;
    5: int i=0;
    6: while(i<bluSt+1)
    7: {
    8: if(A[i]==0)
    9: {
    10: std::swap(A[i],A[redSt]);
    11: redSt++;
    12: i++;
    13: continue;
    14: }
    15: if(A[i] ==2)
    16: {
    17: std::swap(A[i],A[bluSt]);
    18: bluSt--;
    19: continue;
    20: }
    21: i++;
    22: }
    23: }


  • 相关阅读:
    SpringBoot2.1.6 整合CXF 实现Webservice
    一次线上CPU高的问题排查实践
    SpringBoot整合升级Spring Security 报错 【The request was rejected because the URL was not normalized】
    Web服务器☞Apache VS Nginx
    PHP 遍历一个文件夹下所有文件和子文件夹的方法
    PHP 使用 header 方式实现文件下载功能
    PHP gd 库添加 freetype
    MySQL varchar 最大长度,text 类型占用空间剖析
    S.O.L.I.D: PHP 面向对象设计的五个基准原则
    PHP不重新编译,单独添加模块扩展的方法
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078952.html
Copyright © 2011-2022 走看看