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

leetcode No75. Sort Colors

时间:2016-08-05 01:01:56      阅读:119      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!