Description Link to heading
Solution Link to heading
Here, we need three pointers l
, r
, idx
, l
for 0
, r
for 2
, idx
for traversing.
When traversing:
if nums[idx] == 0
,swap(nums[idx], nums[l]);
, andidx++; l++
if nums[idx] == 1
,idx++;
if nums[idx] == 2
,swap(nums[idx], nums[r]);
, and onlyr--
, because newnums[idx]
may be0
or1
or2
, so we need determine the value ofnums[idx]
again.- if
swap(nums[idx], nums[l]);
, newnums[idx]
will be0
only whenidx == l
, ornums[idx] == 1
, so we can increaseidx
.
Code Link to heading
class Solution {
public:
void sortColors(vector<int> &nums) {
int tmp = 0, index = 0;
int l = 0, r = nums.size() - 1;
while (index <= r) {
if (nums[index] == 0) {
tmp = nums[l];
nums[l++] = 0;
nums[index++] = tmp;
} else if (nums[index] == 2) {
tmp = nums[r];
nums[r--] = 2;
nums[index] = tmp;
} else
index++;
}
}
};