Fork me on GitHub

Sort colors

Linkage

https://leetcode.com/problems/sort-colors/description/

Idea

0……0 1……1 x1 x2 …. xm 2…..2

​ | | |

​ left i right

Code

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
class Solution {
public void sortColors(int[] nums) {
//[left, right] is 1

int left=0, right=nums.length - 1;
int i = 0;
while(i <= right) {
if(nums[i]==0) {
swap(nums, i++, left++);
continue;
}if(nums[i]==1) {
i++;
continue;
}
if(nums[i]==2) {
swap(nums, i, right--);
continue;
}

}
}

public void swap(int[] array, int left, int right) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
}