[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);
}
}
一共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);
}
}
相关文章推荐
- lintcode-medium-Sort Colors II
- Lintcode - sort colors II
- [刷题]Sort Colors II
- 九章算法面试题70 排颜色II sort colors
- Wiggle Sort && Wiggle SortII---lintcode
- [LintCode] Wiggle Sort II 扭动排序之二
- lintcode:Sort Colors II
- LintCode "Sort Colors II"
- [LintCode] 颜色分类 Sort Colors
- 143. Sort Colors II
- lintcode-medium-Sort Colors
- Sort Colors II
- #143 Sort Colors II
- Lintcode: Sort Colors II 解题报告
- LintCode-Sort Colors II
- Lintcode: Sort Colors II
- Sort Colors II
- Sort Colors,Search in Rotated Sorted Array I,II,Merge Intervals,Insert Interval,Subsets II
- sort-colors-ii
- LintCode 143. Sort Colors II