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?

    Solution:

    应该用双指针,一个在头一个在尾,这样就可以分割数组。 头为red,故找个一个red,交换位置头指针++; 尾为blue,故找到一个blue,交换位置同时尾指针--。

     1 public class Solution {
     2     public void sortColors(int[] A) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int red = 0;
     6         int blue = A.length - 1;
     7         int i = 0;
     8         while(i <= blue){
     9             if(A[i] == 0){
    10                 A[i] = A[red];
    11                 A[red] = 0;
    12                 red ++;
    13                 i ++;
    14             }else if(A[i] == 2){
    15                 A[i] = A[blue];
    16                 A[blue] = 2;
    17                 blue --; 
    18             }else{
    19                 i ++;
    20             }
    21         }
    22     }
    23 }

     第三遍:

     1 public class Solution {
     2     public void sortColors(int[] A) {
     3         int red = 0, white = 0;
     4         if(A == null || A.length == 0) return;
     5         for(int i = 0; i <A.length; i ++){
     6             if(A[i] == 0) red ++;
     7             else if(A[i] == 1) white ++;
     8         }
     9         for(int i = 0; i < A.length; i ++){
    10             if(red > 0){
    11                 A[i] = 0;
    12                 red --;
    13             }else if(white > 0){
    14                 A[i] = 1;
    15                 white --;
    16             }else
    17                 A[i] = 2;
    18         }
    19     }
    20 }
  • 相关阅读:
    熟悉常用的Linux操作
    Python基础综合练习
    简易c语言文法
    词法分析程序
    组合数据类型综合练习
    综合练习:词频统计
    词法分析程序2
    我对编译原理的理解
    【分享】博客美化(6)为你的博文自动添加目录
    python爬虫的基本思路
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3348370.html
Copyright © 2011-2022 走看看