首页 > 其他 > 详细

leetcode_num75_sort colors

时间:2015-04-01 11:22:04      阅读:190      评论:0      收藏:0      [点我收藏+]

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.

只遍历一次的方法,快速排序的变身版

class Solution {
public:
    void sortColors(int A[], int n) {
        if(A==NULL ||n<=0)
            return;
        int i=0,lo=0,hi=n-1;
        while(i<=hi){
            if (A[i]>1)
                swap(A[i],A[hi--]);
            else if(A[i]<1)
                swap(A[i++],A[lo++]);
            else
                i++;
        }
    }
    void Swap(int &a,int &b){
        int temp=a;
        a=b;
        b=temp;
    }
};


leetcode_num75_sort colors

原文:http://blog.csdn.net/eliza1130/article/details/44804003

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!