-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path75. Sort Colors
46 lines (45 loc) · 1.19 KB
/
75. Sort Colors
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution
{
public:
void sortColors(vector<int>& nums)
{
int pos=0;
int end=nums.size()-1;
int num=end;
int temp;
if(end==0)//no need to sort
return;
bool flag = true;//should continue or not
while(true)
{
while((pos<=num)&&(nums[pos]==0)&&(pos<end))//when red,continue
++pos;
if(pos==end)
break;//all read have sorted
while((end>=0)&&(nums[end]!=0)&&(pos<end))//when not red ,continue
--end;
if(pos==end)
break;
nums[end]=nums[pos];
nums[pos]=0;
++pos;
//--end;
}
end=num;
while(true)
{
while((pos<=num)&&(nums[pos]==1)&&(pos<end))//when white,continue
++pos;
if(pos==end)
break;//all read have sorted
while((end>=0)&&(nums[end]!=1)&&(pos<end))//when not white ,continue
--end;
if(pos==end)
break;
nums[end]=nums[pos];
nums[pos]=1;
++pos;
//--end;
}
}
};