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.
测试代码(c++):
class Solution {
public:
void sortColors(vector<int>& nums) {
int left = 0;
int right = nums.size()-1;
int i = 0;
int time = nums.size();
int flag = 1;
while(i>=left&&i<=right)
{
if(nums[i]==0)
{
swap(nums[i],nums[left]);
left++;
i = left;
flag = 1;
}else if(nums[i]==1)
{
i += flag;
}else{
swap(nums[i],nums[right]);
right--;
i = right;
flag = -1;
}
cout<<left;
}
}
};
性能:
参考答案(C++):
class Solution {
public:
void sortColors(vector<int>& nums) {
int i = 0 , j = 0 , k = 0;
for(int v : nums){
if(v == 0){
nums[k++] = 2;
nums[j++] = 1;
nums[i++] = 0;
}
else if(v == 1){
nums[k++] = 2;
nums[j++] = 1;
}
else nums[k++] = 2;
}
}
};
性能:
参考答案(python):
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i = j = 0
for k in xrange(len(nums)):
v = nums[k]
nums[k] = 2
if v < 2:
nums[j] = 1
j += 1
if v == 0:
nums[i] = 0
i += 1