题目链接:https://leetcode.com/problems/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.
代码:
class Solution {
public:
void sortColors(vector<int>& nums) {
vector<int> nums0;
vector<int> nums1;
vector<int> nums2;
for(int i=0;i<nums.size();i++)
{
if(nums[i]==0)
nums0.push_back(0);
else if(nums[i]==1)
nums1.push_back(1);
else
nums2.push_back(2);
}
nums0.insert(nums0.end(),nums1.begin(),nums1.end());
nums0.insert(nums0.end(),nums2.begin(),nums2.end());
nums=nums0;
}
};
思路2:参考别人的,用双指针,将0交换到前面,2交换到末尾,1不用操作,时间复杂度为O(n),空间复杂度为O(1)
代码:
class Solution {
public:
void sortColors(vector<int>& nums) {
int red=0,blue=nums.size()-1;
for(int i=0;i<blue+1;)
{
if(nums[i]==0)
swap(nums[i++],nums[red++]);
else if(nums[i]==2)
swap(nums[i],nums[blue--]);
else
i++;
}
}
};
参考链接:http://www.acmerblog.com/leetcode-solution-sort-colors-6350.html