您的位置:首页 > 其它

[LintCode]Sort Colors II

2017-04-07 17:29 267 查看
http://www.lintcode.com/en/problem/sort-colors-ii/

一共k种颜色,进行排序

快排思想,找到fromColor到toColor的中点mid,将colors分为小于等于mid的和大于mid的两个部分,然后递归排序

class Solution {
public void sortColors2(int[] colors, int k) {
// write your code here
qSort(colors, 0, colors.length - 1, 1, k);
}
private void qSort(int[] colors, int left, int right, int fromCol, int toCol) {
if (left >= right) {
return;
}
if (fromCol >= toCol) {
return;
}
int mid = fromCol + (toCol - fromCol) / 2;
int beg = left;
int end = right;
while (beg <= end) {
while (beg <= end && colors[beg] <= mid) {
beg++;
}
while (beg <= end && colors[end] > mid) {
end--;
}
if (beg <= end) {
int temp = colors[beg];
colors[beg] = colors[end];
colors[end] = temp;
beg++;
end--;
}
}
qSort(colors, left, end, fromCol, mid);
qSort(colors, beg, right, mid + 1, toCol);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: