首页 > 其他 > 详细

LeetCode: Sorted Color

时间:2015-05-04 09:53:59      阅读:157      评论:0      收藏:0      [点我收藏+]

Title:

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(vector<int>& nums) {
        int *c = new int [3];
        memset(c,0,sizeof(int)*3);
        for (int i = 0; i < nums.size(); i++){
            c[nums[i]]++;
        }
        nums.clear();
        for (int i = 0 ; i < 3; i++){
            for (int j = 0 ; j < c[i]; j++){
                nums.push_back(i);
            }
        }
    }
};

也可以遍历一次就能得到结果,使用3个下标,分别指向0,1,2对应的下标位置。可以这么理解,最左边是0,最右边是2,中间遇到1不用管

class Solution {
public:
    void sortColors(int A[], int n) {
        if(n <= 1) return;
        int start = -1, end = n;
        int p = 0;
        while(p < n && start < end){
            if(A[p] == 0){
                if(p > start) swap(A, ++start, p);
            }else if(A[p] == 2){
                if(p < end) swap(A, p, --end);
            }else ++p;
        }
    }
private:
    void swap(int A[], int i, int j){
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
    }
};

 

LeetCode: Sorted Color

原文:http://www.cnblogs.com/yxzfscg/p/4475382.html

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