首页 > 其他 > 详细

[Leetcode]Sort Colors

时间:2015-03-17 23:17:49      阅读:282      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!