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
  • 相关阅读:
    OC 属性关键字
    OC NSArray数组排序
    OC NSNumber和NSValue和NSDate和NSData
    OC Foundation框架—字符串操作方法及习题
    OC 类对象和类加载
    OC Xcode中常见的错误
    OC self注意事项
    OC 弱语法
    OC 对象和函数
    [Android算法] bitmap 将图片压缩到指定的大小
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3545252.html
Copyright © 2011-2022 走看看