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: }


  • 相关阅读:
    PHP多进程编程
    2013年中国数据库大会PPT
    python学习笔记
    策略分析方法论
    Linux操作系统下定时发送邮件
    PHP初学
    Linux操作下的进程管理利器 Supervise
    Hive中小表与大表关联(join)的性能分析zz
    工作杂记4
    PostgreSQL 13 源码安装【转载】 规格严格
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078952.html
Copyright © 2011-2022 走看看