您的位置:首页 > 其它

Medium 75题 Sort Colors

2016-09-24 13:33 330 查看
Question:

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.

Note:

You are not suppose to use the library's sort function for this problem.

Solution:

思路很容易想到,put all the 0 in the front and 2 in the the back...  but there are several places we should pay attention to...

we should re-check the number after swap.

public class Solution {
public void sortColors(int[] nums) {
int n=nums.length;
int first=0;
int last=n-1;
for(int i=0;i<=n-1&&last!=0&&first!=n-1&&first!=last;i++)
{
if(nums[i]==2)
{
if(i<last)
{
int tmp=nums[i];
nums[i]=nums[last];
nums[last]=tmp;
last--;
i--;
}
else if(i==last)
{
last--;
}
continue;
}
if(nums[i]==0)
{
if(i>first)
{
int tmp=nums[i];
nums[i]=nums[first];
nums[first]=tmp;
first++;
i--;
}
else if(i==first)
{
first++;
}
continue;
}
}
}
}


9/30 第二次看了discussion,由于从前往后遍历,循环有顺序问题,因为第一个循环有可能交换过来一个0,要么就破坏了

int n=nums.length;
int zero=0;
int two=n-1;
for(int i=0;i<=two;i++)
{
while(nums[i]==2&&i<two)
{
//swap(nums[i],nums[two--])
int tmp=nums[i];
nums[i]=nums[two];
nums[two]=tmp;
two--;
}
while(nums[i]==0&&i>zero)
{
//swap(nums[i],nums[zero++]);
int tmp=nums[i];
nums[i]=nums[zero];
nums[zero]=tmp;
zero++;
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: