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.

    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?

    例如10022

    20021->10022->20012->10022->00122

    class Solution {
    public:
        void sortColors(int A[], int n) {
            int p0=0,p1=n-1,p2=n-1;
            while(p0<=p1){
                if(A[p0]==2){
                    int t=A[p2];
                    A[p2]=A[p0];
                    A[p0]=t;
                    p2--;
                    if(p2<p1)p1=p2;
                }
                else if(A[p0]==1){
                    int t=A[p1];
                    A[p1]=A[p0];
                    A[p0]=t;
                    p1--;
                }
                else{
                    p0++;
                }
                
            }
            
        }
    };
    
  • 相关阅读:
    Docker的使用
    Django常见问题
    Linux系统使用
    Nginx
    Redis
    MySQL基础、主从复制、优化
    Python常见的问题
    Python基础知识
    Vue的使用
    python监控tomcat日记文件
  • 原文地址:https://www.cnblogs.com/superzrx/p/3330521.html
Copyright © 2011-2022 走看看