[leetcode]75. Sort Colors三色排序

时间:2021-06-20 14:18:56

Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: You are not suppose to use the library's sort function for this problem.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

思路:

fb的高频题,边界处理很容易出bug,要小心

扫一遍,maintain四个区域,

[leetcode]75. Sort Colors三色排序

0 0  |  1 1 | XXXX |2 2
[0, zero) = 0
[zero, i) = 1
[i, two] = unchecked elements
(two, len-1] = 2

代码:

 /**
0 0 | 1 | xxx | 2 if x == 1:
0 0 | 1 | 1 xx | 2
^
0 0 | 1 | 1 xx | 2
^ if x == 2:
0 0 | 1 | 2xx | 2
^i ^two
0 0 | 1 | x x 2| 2
^i ^two if x == 0:
0 0 | 1 | 0 xx | 2
^zero ^i
0 0 | 0 | 1 xx | 2
^i
**/ class Solution {
public void sortColors(int[] nums) {
// corner
if(nums == null || nums.length == 0) return ; int zero = -1; // nums[0...zero] = 0
int two = nums.length; // nums[two...nums.length-1] = 2
int i = 0; while(i < two){
if(nums[i] == 1){
i++;
}else if(nums[i] == 2){
two--; // to reserve a room
swap(nums, i , two);
}else{ // nums[i] == 0
zero++; // to reserve a room
swap(nums, i , zero);
i++;
}
}
}
private void swap(int[] nums, int a, int b){
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
}