zoukankan      html  css  js  c++  java
  • Leetcode 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?

    类似快排的方法
    void sortColors(int A[], int n){
        int redIndex = 0, blueIndex = n-1;
        while(A[redIndex]  == 0) redIndex++;
        while(A[blueIndex] == 2) blueIndex--;
        int index = redIndex;
        while(index <= blueIndex){
            if(A[index] == 0) swap(A[index++],A[redIndex++]);
            else if(A[index] == 2) swap(A[index],A[blueIndex--]);
            else index++;
        }
    }
  • 相关阅读:
    用before 和after 清除浮动
    清除浮动最优
    pc端布局03
    PC端布局02
    >PC端常用布局01
    浮动
    盒模型-
    盒模型-外边距合并
    spring中的AOP
    AOP的概念
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3630780.html
Copyright © 2011-2022 走看看