private static void swap(int[] colors, int right, int cur) {
int temp = colors[right];
colors[right] = colors[cur];
colors[cur] = temp;
}
public static void sortColors21(int[] colors, int k) {
int start = 0, end = colors.length - 1, count = 0;
while (count < k) {
int min = Integer.MAX_VALUE, 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, right = end, cur = start;
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 += 2;
start = left;
end = right;
}
}
sort k color
最新推荐文章于 2021-02-21 12:07:16 发布