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?

     1 class Solution {
     2 public:
     3     void sortColors(int A[], int n) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         int i = 0; // 0 pointer
     7         int j = n - 1; // 1 pointer
     8         int k = n - 1; // 2 pointer
     9         
    10         while (i <= j)
    11         {
    12             if (A[i] == 2)
    13             {
    14                 int t = A[k];
    15                 A[k] = A[i];
    16                 A[i] = t;
    17                 k--;
    18                 if (k < j)
    19                     j = k;
    20             }
    21             else if (A[i] == 1)
    22             {
    23                 int t = A[j];
    24                 A[j] = A[i];
    25                 A[i] = t;
    26                 j--;
    27             }
    28             else
    29                 i++;
    30         }
    31     }
    32 };
  • 相关阅读:
    MongodDB数据库安装和简单使用
    比较运算符
    Java习题
    JavaScript示例
    Java面向过程练习题7
    Java面向过程练习题6
    倒金字塔
    包含contains
    String 比较
    单词表
  • 原文地址:https://www.cnblogs.com/chkkch/p/2787739.html
Copyright © 2011-2022 走看看