Sort Color
please think about about the while exit condition!!
class Solution{
public:
/**
* @param nums: A list of integer which is 0, 1 or 2
* @return: nothing
*/
void sortColors(vector<int> &nums) {
// write your code here
if(nums.size() == 0)
{
return ;
}
int l = 0;
int i = 0;
int r = nums.size()-1;
while(i <= r)
{
if(nums[i] == 0)
{
swap(nums, l++, i++);
}
else if(nums[i] == 1)
{
i++;
}
else
{
swap(nums, i, r--);
}
}
}
void swap(vector<int>& nums, int left, int right)
{
int t = nums[left];
nums[left] = nums[right];
nums[right] = t;
}
};
code 2
class Solution {
public:
void sortColors(vector<int>& nums) {
int n = nums.size();
if(n == 0)
{
return ;
}
int i = 0;
int j = 0;
int k = n-1;
while(j <= k)
{
if(nums[j] == 0)
{
swap(nums, i, j);
i++;
j++;
}
else if(nums[j] == 1)
{
j++;
}
else
{
swap(nums, j, k);
k--;
}
}
}
void swap(vector<int>& nums, int i, int j)
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
};