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.

    本题改进的地方:

    注释了 j = j-1;

    并在后面加上了while(a[j]==1||a[j]==2)j--;

    主要原因是, 有可能没有2的时候, j就不能从j-1的地方开始了

    class Solution {
    public:
        void swap(int& a, int& b)
        {
            int temp = a;
            a = b;
            b = temp;
        }
        void sortColors(int A[], int n)
        {
            if(n==0)
                return;
            int i = 0, j = n-1;
            for(;i<j;)
            {
                while(A[j]==2)j--;
                while(A[i]==0||A[i]==1)i++;
                if(i<j)
                swap(A[i],A[j]);
            }
            i = 0;
            //j = j-1;
            for(;i<j;)
            {
                while(A[j]==1||A[j]==2)j--;
                while(A[i]==0)i++;
                if(i<j)
                swap(A[i],A[j]);
            }
        }
    };


    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    页面性能
    js运行机制
    渲染机制
    通信类
    js面向对象 继承
    原型
    [HEOI2016/TJOI2016]求和
    「NOIP2018 保卫王国」
    「LGP4719【模板】动态dp」
    多项式进阶操作
  • 原文地址:https://www.cnblogs.com/vintion/p/4116907.html
Copyright © 2011-2022 走看看