Sort Colors
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]Solution
public class Solution {
/**
* @param nums: A list of integer which is 0, 1 or 2
* @return: nothing
*/
public void sortColors(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
int pl = 0, pr = nums.length - 1;
int index = 0;
while (index <= pr) {
if (nums[index] == 0) {
swap(nums, pl, index);
index++;
pl++;
}
else if (nums[index] == 2) {
swap(nums, pr, index);
pr--;
}
else {
index++;
}
}
}
private void swap(int[] nums, int a, int b) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
}Reference
Last updated