题目链接:https://leetcode.com/problems/sort-colors/#/description
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.
方法一:思路:计数排序
class Solution{
public:
void sortColors(vector<int>& nums)
{
int size=nums.size();
int i=0,j=0,k=0;
for(int p=0;p<size;p++)
{
if(nums[p]==0)
i++;
else if (nums[p]==1)
j++;
else if(nums[p]==2)
k++;
}
for(int p=0;p<size;p++)
{
if(p<i)
nums[p]=0;
else if(p>=i && p<i+j)
nums[p]=1;
else
nums[p]=2;
}
}
};
方法二:
思路:left记录左边第一个1的位置,right记录第一个2左边的位置,left的左边全是0,right的右边全是2。
从左到右扫描一次,遇到0就换到左边,遇到1就跳过,遇到2就换到右边,由于left记录的肯定是1,所以交换后i要前进一次,由于right记录的可能是0,可能是1,所以交换后,i不能前进,
class Solution{
public:
void sortColors(vector<int>& nums)
{
int size=nums.size();
int left=0,right=size-1;
int i=0;
while(i<=right)
{
if(nums[i]==0)
{
swap(nums[i],nums[left]);
left++;
i++;
}
else if(nums[i]==1)
{
i++;
}
else
{
swap(nums[i],nums[right]);
right--;
}
}
}
};
方法三:
class Solution{
public:
void sortColors(vector<int>& nums)
{
int size=nums.size();
int i=-1,j=-1,k=-1;
for(int p=0;p<size;p++)
{
if(nums[p]==0)
{
nums[++k]=2;
nums[++j]=1;
nums[++i]=0;
}
else if(nums[p]==1)
{
nums[++k]=2;
nums[++j]=1;
}
else if(nums[p]==2)
{
nums[++k]=2;
}
}
}
};