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

【LeetCode OJ 075】Sort Colors

时间:2016-03-28 00:08:14      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/sort-colors/

题目: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.

解题思路如下:遍历数组,存储每种颜色的个数,再进行排序,示例代码如下:

/**
 * @Description:
 * 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.
 * @author 徐剑   
 * @date 2016年3月27日 下午12:32:14 
 * @version V1.0
 */
public class Solution
{	
	 public static void sortColors(int[] nums)
	 {
	        if(nums==null||nums.length<=0)
	        	return;
	        int a[]=new int[3];
	        for(int i=0;i<nums.length;i++)
	        {
	        	a[nums[i]]++;
	        }
	        int x=0;
	        int y=0;
	        int z=0;
	        for(int i=0;i<nums.length;)
	        {
	        	while(x<a[0])
	        	{
	        		x++;
	        		nums[i]=0;
	        		i++;
	        		continue;
	        	}
	        	while(y<a[1])
	        	{
	        		y++;
	        		nums[i]=1;
	        		i++;
	        		continue;
	        	}
	        	while(z<a[2])
	        	{
	        		z++;
	        		nums[i]=2;
	        		i++;
	        		continue;
	        	}
	        }
	 }
}


【LeetCode OJ 075】Sort Colors

标签:

原文地址:http://blog.csdn.net/xujian_2014/article/details/50991185

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