• Sort Colors


    Link:http://oj.leetcode.com/problems/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?

    Two-pass code:

     1 public void sortColors(int A[]) {
     2         if (A.length <= 1)
     3             return;
     4         int red = 0, white = 0;
     5         for (int i = 0; i < A.length; i++) {
     6             if (A[i] == 0)
     7                 red++;
     8             if (A[i] == 1)
     9                 white++;
    10         }
    11         int index = 0;
    12         while (red-- > 0) {
    13             A[index++] = 0;
    14         }
    15         while (white-- > 0) {
    16             A[index++] = 1;
    17         }
    18         while (index < A.length) {
    19             A[index++] = 2;
    20         }
    21     }

    One-Pass version:

     1 public void sortColors(int[] A) {
     2         if (A.length <= 1)
     3             return;
     4         int red = 0, index = 0, blue = A.length - 1;
     5         while (index <= blue) {
     6             if (A[index] == 0) {
     7                 int temp = A[red];
     8                 A[red++] = A[index];
     9                 A[index++] = temp;
    10                 continue;
    11             }
    12             if (A[index] == 2) {
    13                 int temp = A[blue];
    14                 A[blue--] = A[index];
    15                 A[index] = temp;
    16                 continue;
    17             }
    18             index++;
    19         }
    20     }

    开挂版:

    1 public void setColors(int A[]) {
    2         Arrays.sort(A);
    3     }
  • 相关阅读:
    svn服务器
    TCopyDataStruct 各个参数意义
    Com+连不上解决办法
    流的压缩与解压缩
    Config 文件的增删改查
    Assembly 操作
    redhat7 安装oracle11.2.4页面显示不全解决方法
    IEnumerator和IEnumerable详解
    [我的阿里云服务器] —— 安装LAMP
    设计模式之二抽象工厂设计模式
  • 原文地址:https://www.cnblogs.com/Altaszzz/p/3713184.html
Copyright © 2020-2023  润新知