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

    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?

    代码:
    用两个指针分别指向两边的0和2,0指针向右移,2指针向左移。
    代码:
     1     void sortColors(int A[], int n) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         int left = 0, right = n-1;
     5         while(A[left] == 0)
     6             left++;
     7         while(A[right] == 2)
     8             right--;
     9         int cur;
    10         while(left < right){
    11             for(cur = left; cur <= right; cur++){
    12                 if(A[cur] == 0){
    13                     A[cur] = A[left];
    14                     A[left++] = 0;
    15                     while(A[left] == 0)
    16                         left++;
    17                     break;
    18                 }
    19                 else if(A[cur] == 2){
    20                     A[cur] = A[right];
    21                     A[right--] = 2;
    22                     while(A[right] == 2)
    23                         right--;
    24                     break;
    25                 }
    26             }
    27             if(cur > right)
    28                 break;
    29         }
    30     }
  • 相关阅读:
    《Qt学习系列笔记》--章节索引
    Qt-绘制图表
    Qt-可视化数据库操作
    Qt-数据库操作SQLite
    古人说的最好,临渊羡鱼,不如退而结网, 这是个勇气问题.
    阿里云产品之数据中台架构
    使用HSDB查看类变量的内存布局(5)
    文件流
    类文件介绍
    类的连接之重写(1)
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3411188.html
Copyright © 2011-2022 走看看