From : 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.
Hide Similar Problems
Solution 1:
统计个数
class Solution {
public:
void sortColors(vector<int>& nums) {
int cnt0=0, cnt1=0, cnt2=0;
for(int i=0, len=nums.size(); i<len; i++) {
int n = nums[i];
if(n == 0) cnt0++;
else if(n == 1) cnt1++;
else cnt2++;
}
for(int i=0; i<cnt0; i++) nums[i] = 0;
for(int i=cnt0, n=cnt0+cnt1; i<n; i++) nums[i] = 1;
for(int i=cnt0+cnt1, n=cnt0+cnt1+cnt2; i<n; i++) nums[i] = 2;
}
};
Solution 2:
双指针
class Solution {
public:
void sortColors(vector<int>& nums) {
int n=nums.size(), i0=-1, i2=n, i=0;
while(i < i2) {
if(nums[i] == 0 && i > i0) {
swap(nums[++i0], nums[i]);
} else if(nums[i] == 2 && i < i2) {
swap(nums[--i2], nums[i]);
} else {
i++;
}
}
}
void swap(int &a, int &b) {
int t=a;
a = b;
b = t;
}
};
class Solution {
public:
void sortColors(vector<int>& nums) {
int i=-1, j=-1, k=-1;
for(int d = 0, len = nums.size(); d < len; d++) {
if(nums[d] == 0) {
nums[++k]=2;
nums[++j]=1;
nums[++i]=0;
} else if (nums[d] == 1) {
nums[++k]=2;
nums[++j]=1;
} else if (nums[d] == 2) {
nums[++k]=2;
}
}
}
};
改进:
class Solution {
public:
void sortColors(vector<int>& nums) {
int i=-1, j=-1;
for(int d = 0, len = nums.size(); d < len; d++) {
int v = nums[d];
nums[d] = 2;
if(v== 0) {
nums[++j]=1;
nums[++i]=0;
} else if (v == 1) {
nums[++j]=1;
}
}
}
};
1410

被折叠的 条评论
为什么被折叠?



