---
# System prepended metadata

title: Sort Colors
tags: [Medium]

---

# Sort Colors
###### tags: `Medium`
>question : https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/798/

>reference : 

>related problem : 
## My Solution
設兩個指標，指向0的最尾端跟2的最前端(也是1的頭跟尾端)
```java=
class Solution {
    public void sortColors(int[] nums) {
        int start = 0;
        int end = nums.length - 1;
        int i = 0;
        while(i <= end) {
            if(nums[i] == 0) {
                swap(start, i, nums);
                start++;
                i++;
                continue;
            }
            if(nums[i] == 2) {
                swap(end, i, nums);
                end--;
                continue;
            }
            i++;
        }
    }
    private void swap(int a, int b, int[] nums) {
        int tmp = nums[a];
        nums[a] = nums[b];
        nums[b] = tmp;
    }
}
```
## Other Solution