首页 > 其他 > 详细

leetcode No75. Sort Colors

时间:2016-08-05 01:01:54      阅读:160      评论:0      收藏:0      [点我收藏+]

Question:

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.

Algorithm:

计数排序,就三个数,分别记下0,1,2的个数,k1、k2、k3。然后置新数组的前k1个数为0,后k2个数为1,剩下的为2。

Accepted Code:

class Solution {  //计数排序
public:
    void sortColors(vector<int>& nums) {
        int k0=0;
        int k1=0;
        int k2=0;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]==0)
                k0++;
            else if(nums[i]==1)
                k1++;
            else 
                k2++;
        }
        for(int i=0;i<nums.size();i++)
        {
            if(i<k0) 
                nums[i]=0;
            else if(i<(k0+k1))
                nums[i]=1;
            else 
                nums[i]=2;
        }
    }
};




leetcode No75. Sort Colors

原文:http://blog.csdn.net/u011391629/article/details/52122521

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