您的位置:首页 > 编程语言 > Java开发

75. Sort Colors

2016-07-28 17:36 399 查看
题目:

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.

将相同颜色物体集在一起,并按序排列。

两个指针,分别指向red和blue

public void sortColors(int[] nums) {
int start=0;
int end=nums.length-1;
for(int i=0;i<end+1;i++)
{
if(nums[i]==0)
{
nums[i++]=nums[start];
nums[start++]=0;
}
else if(nums[i]==2)
{
nums[i++]=nums[end];
nums[end--]=2;
}
else
{
i++;
}
}
}分别统计每个物体的个数:
public void sortColors(int[] nums) {
int sum=0;
int count=0;
for(int i=0;i<nums.length;i++)
{
sum+=nums[i];
if(nums[i]==1)count++;
}

int count2 = (sum-count)/2;
int count0 = nums.length-count-count2;
for(int i=0;i<count0;i++)
{
nums[i]=0;
}
for(int i=count0;i<count0+count;i++)
{
nums[i]=1;
}
for(int i=count0+count;i<nums.length;i++)
{
nums[i]=2;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java