• 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]);
            }
        }
    };


    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    粘包_Server
    初见UDP_Server
    初见UDP_Client
    TCP/UDP协议
    网络编程相关概念
    mmap实现大文件快速拷贝
    生成这消费者问题(多线程实现)
    线程同步互斥实现资源访问
    信号灯(线程互斥)
    线程属性
  • 原文地址:https://www.cnblogs.com/vintion/p/4116907.html
Copyright © 2020-2023  润新知