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

[leetcode-75-Sort Colors]

时间:2017-06-02 11:43:16      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:ace   turn   for   cti   思路   统计   void   i++   pos   

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.
Note:
You are not suppose to use the library‘s sort function for this problem.

思路:

首先扫描一遍,统计不同元素个数。

类似于two pointers概念。

void sortColors(vector<int>& nums)
     {
         if (nums.size() <= 1)return;
         vector<int>temp = nums;
         int zero = 0, one = 0, two = 0, index0 = 0, index1 = 0, index2 = 0;
         for (int i = 0; i < nums.size();i++)
         {
             if (nums[i] == 0)zero++;
             if (nums[i] == 1)one++;
             if (nums[i] == 2)two++;             
         }
         index1 = zero, index2 = zero + one;
         for (int i = 0; i < temp.size(); i++)
         {
             if (temp[i] == 0)nums[index0++] = 0;
             if (temp[i] == 1)nums[index1++] = 1;
             if (temp[i] == 2)nums[index2++] = 2;
         }
     }

 

[leetcode-75-Sort Colors]

标签:ace   turn   for   cti   思路   统计   void   i++   pos   

原文地址:http://www.cnblogs.com/hellowooorld/p/6932066.html

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