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?

     
    用i记录0应该放的位置,j记录2应该放的位置。
    cur从0到j扫描,
    遇到0,放在i位置,i后移;
    遇到2,放在j位置,j前移;
    遇到1,cur后移。
    扫描一遍得到排好序的数组。
    时间O(n)且一次扫描,空间O(1),满足要求。
    这么做的前提是,拿到一个值,就知道它应该放在哪儿。(这点和快排的根据pivot交换元素有点像)
     
     1 public class Solution {
     2     public void sortColors(int[] A) {
     3         int len = A.length;
     4         int redIndex = 0, blueIndex = len -1;
     5         int i = 0;
     6         while(i< blueIndex+1){
     7             if(A[i] == 0){
     8                 swap(A,i, redIndex);
     9                 redIndex++;
    10                 i++;
    11             }else if(A[i] == 2){
    12                 swap(A, i, blueIndex);
    13                 blueIndex--;
    14             }else{
    15                 i++;
    16             }
    17         }
    18     }
    19     
    20     private void swap(int[] A, int i, int j){
    21         int temp = A[i];
    22         A[i] = A[j];
    23         A[j] =temp;
    24     }
    25 }
    View Code
  • 相关阅读:
    页面状态加载.... JS
    创建windows服务&监控SQL数据运行状态(原)
    为图片添加锚点
    当jquery遇上了json 哇哈哈
    关于SVN源代码管理
    最新最全的ASP.NET学习资源大全
    .NET开发人员必知的八个网站
    关于回车执行(回车触发事件)
    DIV+CSS布局
    优化Linux下的内核TCP参数来提高服务器负载能力
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3545252.html
Copyright © 2011-2022 走看看