Sort Colors
Total Accepted: 51484 Total Submissions: 157920My Submissions
Question Solution
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.
Show Tags
public class Solution {
public void sortColors(int[] nums) {
int l=nums.length;
if(l==2)
{
if(nums[0]>nums[1])
{
int m=nums[0];
nums[0]=nums[1];
nums[1]=m;
}
}
else if(l>2)
{
int s=0;
int e=l-1;
int v=-1;
int min=3;
int max=-1;
int minid=-1;
int maxid=-1;
for(int i=0;i<l;i++)
{
if(nums[i]<min)
{
min=nums[i];
minid=i;
}
}
nums[minid]=nums[0];
nums[0]=min;
for(int i=0;i<l;i++)
{
if(nums[i]>max)
{
max=nums[i];
maxid=i;
}
}
nums[maxid]=nums[l-1];
nums[l-1]=max;
if(max!=min)
{
/*
boolean open1=false;
boolean open2=false;
for(int i=0;i<l;i++)
{
if(open1&&open2)
break;
if(nums[i]==0&&!open1)
{
nums[i]=nums[0];
nums[0]=0;
i--;
open1=true;
}
else if(nums[i]==2&&!open2)
{
nums[i]=nums[l-1];
nums[l-1]=2;
i--;
open2=true;
}
}
*/
while(s<e-1&&v<e-1){
if(v==-1)
{
if(nums[s]==nums[e]){
int m=nums[s+1];
nums[s+1]=nums[e];
nums[e]=m;
s++;
}
else{
while(nums[s]==nums[s+1]&&s<e-1)
s++;
while(nums[e]==nums[e-1]&&s<e-1)
e--;
if(s==e-1)
break;
else
{
if(nums[s+1]==nums[e])
{
int m=nums[s+1];
nums[s+1]=nums[e-1];
nums[e-1]=m;
e--;
}
else if (nums[s]==nums[e-1])
{
int m=nums[e-1];
nums[e-1]=nums[s+1];
nums[s+1]=m;
s++;
}
else{
v=s+1;
if(v>=e-2)
break;
else
{
int m=nums[e-1];
nums[e-1]=nums[v+1];
nums[v+1]=m;
v++;
}
}
}
}
}
else
{
while(nums[e]==nums[e-1]&&v<e-1)
e--;
if(v==e-1)
break;
if(nums[e-1]==nums[v])
if(v==e-2)
break;
else
{
int m=nums[e-1];
nums[e-1]=nums[v+1];
nums[v+1]=m;
v++;
}
else{
int m=nums[e-1];
nums[e-1]=nums[v+1];
nums[v+1]=m;
m=nums[v+1];
nums[v+1]=nums[s+1];
nums[s+1]=m;
s++;
v++;
}
}
}
}
System.out.print("y");
}
}
}