参考点击打开链接
每次只对两个颜色min 和max排序,其他的都不变,于是中间再用I的方法即可求解。
class Solution {
/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/
public void sortColors2(int[] colors, int k) {
// write your code here
int start = 0, end = colors.length - 1, count = 0;
while (count < k) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = start; i <= end; i++) {
min = Math.min(min, colors[i]);
max = Math.max(max, colors[i]);
}
int left = start, cur = start, right = end;
while (cur <= right) {
if (colors[cur] == min) {
swap(colors, left, cur);
left++;
cur++;
} else if (colors[cur] > min && colors[cur] < max) {
cur++;
} else {
swap(colors, right, cur);
right--;
}
}
count = count + 2;
start = left;
end = right;
}
}
private void swap(int[] colors, int right, int cur) {
int temp = colors[right];
colors[right] = colors[cur];
colors[cur] = temp;
}
}