题目
链接:https://leetcode.com/problems/sort-colors/
**Level: ** Medium
Discription:
Given an array with n objects colored red, white or blue, sort them in-place 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.
Example 1:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Note:
- You are not suppose to use the library's sort function for this problem.
- Could you come up with a one-pass algorithm using only constant space?
代码
class Solution {
public:
void sortColors(vector<int>& nums) {
if(nums.size()<=1)
return;
int fa=0;
int fc=nums.size()-1;
int fb=0;
while(fb<=fc)
{
if(nums[fb]==0)
{
swap(nums[fa], nums[fb]);
fa++;
fb++;
}
else if(nums[fb]==2)
{
swap(nums[fb], nums[fc]);
fc--;
}
else
{
fb++;
}
}
return;
}
};
思考
- 算法时间复杂度为O((n)),空间复杂度为O((1) )。
- 题目要求一次遍历,in-place完成,采用三指针,首尾两个指针,中间一个指针。中间指针取到1时,往后移动,如果为0,则和首指针互换,首指针和中间指针均往后移一位。如果为2,则和尾指针互换,尾指针向前移一位。当中间指针移动到比尾指针还大时跳出循环。