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;
}
}
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;
}
}
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序