码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_num75_sort colors

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

标签:c++   leetcode   排序算法   

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

标签:c++   leetcode   排序算法   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!