zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    Spring 框架的设计理念与设计模式分析
    stratos paas平台
    云计算国际标准
    如何在KVM中管理存储池
    深度学习(四) softmax函数
    深度学习(二)BP求解过程和梯度下降
    深度学习(一) BP神经网络
    提交代码到git
    Mac 安装tensorflow
    Mac 安装Git
  • 原文地址:https://www.cnblogs.com/Altaszzz/p/3713184.html
Copyright © 2011-2022 走看看