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

[Leetcode]Sort Colors

时间:2015-03-17 23:20:05      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

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.

记录每个颜色出现多少次就好了,然后按顺序把原数组的值改变。

 1 class Solution {
 2 public:
 3     void sortColors(int A[], int n) {
 4         int num1,num2,num3,i;
 5         num1=num2=num3=0;
 6         for(i=0;i<n;i++)
 7         {
 8            if(A[i]==0) num1++;
 9            if(A[i]==1) num2++;
10            if(A[i]==2) num3++;
11         }
12         int k=0;       
13         while(num1--) A[k++]=0;
14         while(num2--) A[k++]=1;
15         while(num3--) A[k++]=2;
16     }
17 };

 

[Leetcode]Sort Colors

标签:

原文地址:http://www.cnblogs.com/desp/p/4345785.html

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