75. Sort Colors
2017-05-14 21:43
197 查看
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.
click to show follow up.
Subscribe to see which companies asked this question
这是一个简单排序问题,所给数组中只有0 , 1 , 2 大小的元素,将其由小及大排序即可。
题目明确要求不可用标准库中的排序算法,尽可能使得算法高效。
我们常用的排序算法最优情况下也有 O(nlogn) 的时间复杂度,对待这样一个特殊的数组排序,我们应该采取其他更加高效的方法。
follow up 给出一种方法,分别计算元素0 , 1 , 2 的个数,然后对原数组重新赋值,简单高效,下面用该
方法给出程序实现。
class Solution {
public:
void sortColors(vector<int>& nums) {
if (nums.empty())
return;
//初始化一个count数组,count[0] , count[1] , count[2] 分别记录nums中0 , 1 , 2出现个数
vector<int> count(3, 0);
vector<int>::iterator iter = nums.begin();
for (; iter != nums.end(); iter++)
{
if (*iter == 0)
count[0]++;
else if (*iter == 1)
count[1]++;
else if (*iter == 2)
count[2]++;
}//for
//对原数组排序
int i = 0;
while (i < count[0])
nums[i++] = 0;
while (i < (count[0] + count[1]))
nums[i++] = 1;
while (i < (count[0] + count[1] + count[2]))
nums[i++] = 2;
return;
}
};
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.
click to show follow up.
Subscribe to see which companies asked this question
分析
这是一个简单排序问题,所给数组中只有0 , 1 , 2 大小的元素,将其由小及大排序即可。题目明确要求不可用标准库中的排序算法,尽可能使得算法高效。
我们常用的排序算法最优情况下也有 O(nlogn) 的时间复杂度,对待这样一个特殊的数组排序,我们应该采取其他更加高效的方法。
follow up 给出一种方法,分别计算元素0 , 1 , 2 的个数,然后对原数组重新赋值,简单高效,下面用该
方法给出程序实现。
class Solution {
public:
void sortColors(vector<int>& nums) {
if (nums.empty())
return;
//初始化一个count数组,count[0] , count[1] , count[2] 分别记录nums中0 , 1 , 2出现个数
vector<int> count(3, 0);
vector<int>::iterator iter = nums.begin();
for (; iter != nums.end(); iter++)
{
if (*iter == 0)
count[0]++;
else if (*iter == 1)
count[1]++;
else if (*iter == 2)
count[2]++;
}//for
//对原数组排序
int i = 0;
while (i < count[0])
nums[i++] = 0;
while (i < (count[0] + count[1]))
nums[i++] = 1;
while (i < (count[0] + count[1] + count[2]))
nums[i++] = 2;
return;
}
};
相关文章推荐
- leetcode note--leetcode 75 Sort Colors
- 个人记录-LeetCode 75. Sort Colors
- [置顶] 75. Sort Colors--荷兰三色国旗问题
- leetcode_middle_62_75. Sort Colors
- [LeetCode] 75. Sort Colors java
- LeetCode 75. Sort Colors
- 75. Sort Colors(unsolved)
- leetcode_question_75 Sort Colors
- [LeetCode] 75. Sort Colors
- LeetCode 75. Sort Colors(排序颜色)
- 75. Sort Colors
- LeetCode 75. Sort Colors
- 75. Sort Colors
- LeetCode OJ 75. Sort Colors
- 【一天一道LeetCode】#75. Sort Colors
- 280. Wiggle Sort && 324. Wiggle Sort II && 75. Sort Colors
- 【Medium】75. Sort Colors
- leetcode 75. Sort Colors
- Medium 75题 Sort Colors
- 75. Sort Colors