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     }
  • 相关阅读:
    IsNull和IsEmpty的区别
    常用正则表达式
    VBScript函数
    SqlCommand类
    ubuntu更新grub
    例解 autoconf 和 automake 生成 Makefile 文件[转+个人修改]
    gEdit: 打造简洁,小巧的编程环境[转]
    Linux 常用命令
    GTK+ 简介
    “菜单” (menubar)和“工具栏”(toolbars)
  • 原文地址:https://www.cnblogs.com/Altaszzz/p/3713184.html
Copyright © 2011-2022 走看看