Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
 * key point 1: use 2 pointer to track the position of last red and first blue.
 */
class Solution {
    public void sortColors(int[] nums) {
        if (nums == null || nums.length < 2) {
            return;
        }
        int r = 0, b = nums.length - 1;
        while (r < nums.length && nums[r] == 0) {
            r++;
        }
        while (b >= 0 && nums[b] == 2) {
            b--;
        }
        int i = r;
        while (i <= b) {
            if (nums[i] == 0) {
                swap(nums, i, r);
                r++;
                while (r < nums.length && nums[r] == 0) {
                    r++;
                }
                i = r;
            } else if (nums[i] == 2) {
                swap(nums, i, b);
                b--;
                while (b >= 0 && nums[b] == 2) {
                   b--;
                }
            } else {
                i++;
            }
        }
    }
    
    public void swap(int[] nums, int i, int j) {
        nums[i] = nums[i]^nums[j];
        nums[j] = nums[i]^nums[j];
        nums[i] = nums[i]^nums[j];
    }
}