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.

    题意:就是给包含0,1,2的数组排序。

    要求只遍历序列一次

    mid不应该从1开始,而需从0开始,这样才能防止A[0]=2

    class Solution {
    public:
        void swap(int* a,int i,int j){
            int temp=a[i];
            a[i]=a[j];
            a[j]=temp;
        }
        void sortColors(int A[], int n) {
            if(A==NULL||n<=1) return;
            int l=0;
            int mid=0;
            int r=n-1;
            while(A[l]==0){++l;++mid;}
            while(A[r]==2) --r;
            while(mid<=r){
                if(A[mid]==1) ++mid;
                else if(A[mid]==2) {swap(A,mid,r);--r;}
                else if(A[mid]==0) {swap(A,mid,l);++l;++mid}
            }
        }
    };
     
  • 相关阅读:
    vue-实践1
    node 基本使用
    vue通信
    初始AMD和Common.js
    vue正确引入第三方包
    常见的java设计模式
    springboot加ES实现全局检索
    Cookie丢失的原因
    动态SQL
    用Java实现给图片添加文字
  • 原文地址:https://www.cnblogs.com/fightformylife/p/4213545.html
Copyright © 2011-2022 走看看