---
# System prepended metadata

title: 0075. Sort Colors
tags: [Leetcode, 双指针, Medium]

---

#  0075. Sort Colors
###### tags: `Leetcode` `Medium` `双指针`
Link: https://leetcode.com/problems/sort-colors/

## 思路
如果是用vector内建的sort，结果是这样的：
Runtime: 4 ms, faster than **47.23%** of C++ online submissions for Sort Colors.
Memory Usage: 8.3 MB, less than **63.90%** of C++ online submissions for Sort Colors.
那这道题跟内建的sort不同的地方就在于，它只有可能有三个元素，那么只需要用两个指针来标识下次再插入0和1，要放在什么位置即可。

##  Code
```c=
class Solution {
public:
    void sortColors(vector<int>& nums) {
        int p0 = 0,p1 = 0;
        for(int i = 0;i < nums.size();i++){
            if(nums[i] == 0){
                swap(nums[i],nums[p0]);
                if(nums[i] == 1){
                    swap(nums[i],nums[p1]);
                }
                p0++;
                p1++;
            }
            else if(nums[i] == 1){
                swap(nums[i],nums[p1]);
                p1++;
            }
        }
    }
};
```
## Best Result
Runtime: 0 ms, faster than **100.00%** of C++ online submissions for Sort Colors.
Memory Usage: 8.3 MB, less than **63.90%** of C++ online submissions for Sort Colors.
