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.
思路:
第一想法是选择一种排序算法,但没必要!
本题需排序的元素仅有0.1.2三个值大量重复,可以考虑直接扫描一遍,统计这三个值出现的个数,再赋值一遍。(避开了交换的代价)
86 / 86 test cases passed. Runtime: 3 ms. Your runtime beats 13.43% of cpp submissions.
另有方法:点击打开链接
思路:设三个位置索引分别标识0.1.2的最后出现位置,默认位置为-1(即不存在该值元素),从0位置开始扫描,若遇到0,则所有位置索引+1;若遇到1,则2,1的位置索引+1,若遇到2,则只有2的位置索引需要后移;
Your runtime beats 13.43% of cpp submissions.
代码如下:
class Solution {
public:
void sortColors(vector<int>& nums) {
int len = nums.size();
/* int num0=0, num1=0, num2=0;
for( int i=0; i<len; ++i ){
switch(nums[i]){
case 0: ++num0; break;
case 1: ++num1; break;
case 2: ++num2; break; //not necessary
}
}
for( int i=0; i<len; ++i ){
if( i<num0 ){
nums[i] = 0;
}else{
if( i>=num0+num1 ){
nums[i] = 2;
}else{
nums[i] = 1;
}
}
}
*/
int loc0 = -1, loc1 = -1, loc2 = -1;
for( int i=0; i<len; ++i ){
if( nums[i]==0 ){
nums[++loc2] = 2;
nums[++loc1] = 1;
nums[++loc0] = 0;
}else{
if( nums[i]==1 ){
nums[++loc2] = 2;
nums[++loc1] = 1;
}else{
nums[++loc2] = 2;
}
}
}
}
};