class Solution {
public:
void swap(vector<int> &data, int i, int j)
{
data[i]^=data[j];
data[j]^=data[i];
data[i]^=data[j];
}
int sort_n(int head, vector<int> &data, int sort_n)
{
int i=head, j=data.size()-1;
while(true)
{
while(i<data.size() && data[i]==sort_n) // i scan from the beginning
{
i++;
}
while(j>=0 && data[j]!=sort_n)
{
j--;
}
if(i<j)
swap (data, i, j);
else
break;
}
return i;
}
void sort(vector<int> &data)
{
int head = sort_n(0, data, 0);
sort_n(head, data, 1);
}
/*
0
1
2
0 0
1 1
0 1
1 0 -> 0 1
*/
void sortColors(int A[], int n) {
vector<int> data(n);
for(int i=0;i<n;i++) data[i]=A[i];
sort(data);
for(int i=0;i<n;i++) A[i]=data[i];
// Start typing your C/C++ solution below
// DO NOT write int main() function
}
};Sort Colors
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.
- 首先我要在纸上,非常非常聪明且迅速且机灵
- 给出几个用例
- 找出边界用例和特殊用例,确定特判条件
- 给出函数头
- 暴力解,简述,优化。
- 给出能够想到的最优价
- 伪代码,同时结合用例
- 真实代码
342

被折叠的 条评论
为什么被折叠?



