leetcode-sort-colors

题目大意

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

  数组中只含有0,1,2三种数,要求排序数组,时间复杂度O(n),并且one-pass,空间复杂度O(1)

题目分析

  双指针,用p0和p1记录下一个需要放入的位置坐标,具体可以看下代码

代码

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
public class Solution {
private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
public void sortColors(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
int len = nums.length;
int p0 = 0;
int p1 = len - 1;
int i = 0;
while (i <= p1) {
if (nums[i] == 0) {
swap(nums, i++, p0++);
} else if (nums[i] == 2) {
swap(nums, i, p1--); // 注意此时i一定不能--
} else {
i++;
}
}
}
}