LeetCode075 Sort Colors

three colors, sort them:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
do it in-place

since it needs to be done in-place, the “only” thing we can do is: using pointers.

so we have three pointers, p, i and j, p controls the right bound of 0s and i controls the right bound of 1s and j controls the left bound of 2s.
so i pointer is like a pioneer, and it moves forward all the time, and check the nums[i]. and i will be stopped whrn i meet with j.

class Solution {
    public void sortColors(int[] nums) {
        int m = nums.length;
        int i = 0; //i is the right bound of 1s
        int j = m - 1; //j is the left bound of 2s
        int p = 0; //p is the right bound of 0s
        while (i <= j) { //i is faster than p, so that's why while statement have i<=j
            if (nums[i] == 0) {
                swap(nums, p, i);
                p++;
                i++;
            } else if (nums[i] == 2) {
                swap(nums, i, j);
                j--;
            } else {
                i++;
            }
        }
    
    }
    
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
posted @ 2020-06-13 01:07  EvanMeetTheWorld  阅读(19)  评论(0)    收藏  举报