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++;
        }
    }
  • 相关阅读:
    学习笔记
    django中嵌入百度editor插件
    定位屡试不爽
    django忘记管理员账号和密码处理
    linux上配置java环境
    python3学习问题汇总
    Android系统框架
    python深复制和浅复制
    装饰器原理和装饰器参数使用
    小白神器
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3630780.html
Copyright © 2011-2022 走看看