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++;
        }
    }
  • 相关阅读:
    文件路径选择中的三态逻辑
    .net版本号
    使用MSBuild编译vs多个解决方案
    CEF截图
    使用SharpZIpLib写的压缩解压操作类
    软件试用期设置
    list转datatable
    excel 导入
    网站登录简单验证码
    UEditor编辑器
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3630780.html
Copyright © 2011-2022 走看看