Lintcode - sort colors II
2015-01-30 14:02
302 查看
Given an array of n objects with k different colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, ... k.
Note
You are not suppose to use the library's sort function for this problem.
Example
GIven colors=[3, 2, 2, 1, 4], k=4, your code should sort colors in-place to [1, 2, 2, 3, 4].
Challenge
A rather straight forward solution is a two-pass algorithm using counting sort. That will cost O(k) extra memory.
Can you do it without using extra memory?
为了省空间,只能花时间了,还是按照sort color的方法,找到当前array中min, max,其余忽略,然后把min/max放到最前和最后。循环直到min/max count = k
复杂度是O(n^2): T(n) = T(n-2) + n
Note
You are not suppose to use the library's sort function for this problem.
Example
GIven colors=[3, 2, 2, 1, 4], k=4, your code should sort colors in-place to [1, 2, 2, 3, 4].
Challenge
A rather straight forward solution is a two-pass algorithm using counting sort. That will cost O(k) extra memory.
Can you do it without using extra memory?
为了省空间,只能花时间了,还是按照sort color的方法,找到当前array中min, max,其余忽略,然后把min/max放到最前和最后。循环直到min/max count = k
复杂度是O(n^2): T(n) = T(n-2) + n
public void sortColors2(int[] colors, int k) { int count = 0; int start = 0; int end = colors.length-1; 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; int right = end; int cur = left; while(cur <= right) { if (colors[cur] == min) { swap(left, cur, colors); cur++; left++; } else if (colors[cur] > min && colors[cur] < max) { cur++; } else { int tmp = colors[cur]; swap(cur, right, colors); right--; } } count += 2; start = left; end = right; } } void swap(int left, int right, int[] colors) { int tmp = colors[left]; colors[left] = colors[right]; colors[right] = tmp; }
相关文章推荐
- [LintCode]Sort Colors II
- lintcode-medium-Sort Colors II
- Lintcode: Sort Colors II
- 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
- [Lintcode]Sort Colors颜色分类
- [LintCode] Sort Integers II 整数排序之二
- Sort Colors I & II
- [刷题]Sort Colors II
- 九章算法面试题70 排颜色II sort colors
- [LintCode] Wiggle Sort II 扭动排序之二
- lintcode:Sort Colors II
- LintCode "Sort Colors II"
- LintCode 143. Sort Colors II
- [LintCode] 颜色分类 Sort Colors
- 143. Sort Colors II
- Wiggle Sort && Wiggle SortII---lintcode