Lintcode - sort colors II
来源:互联网 发布:南京品浪钓具淘宝店铺 编辑:程序博客网 时间:2024/06/09 14:28
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
为了省空间,只能花时间了,还是按照sort color的方法,找到当前array中min, max,其余忽略,然后把min/max放到最前和最后。循环直到min/max count = kA 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?
复杂度是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; }
0 0
- Lintcode - sort colors II
- lintcode:Sort Colors II
- [LintCode]Sort Colors II
- LintCode 143. Sort Colors II
- lintcode:Sort Colors
- [刷题]Sort Colors II
- sort-colors-ii
- Sort Colors II
- #143 Sort Colors II
- [LintCode] 颜色分类 Sort Colors
- [Lintcode]Sort Colors颜色分类
- LintCode Wiggle Sort II
- 143.Sort Colors II-排颜色 II(中等题)
- Sort Colors
- sort colors
- Sort Colors
- Sort Colors
- Sort Colors
- Ubuntu 9.10 SSH的安装与使用
- spring定时器配置
- 使用innodb_data_file_path修改数据文件位置,发生The server quit without updating PID file错误的解决原因及方法。
- iOS strong和weak
- JAVA中文排序
- Lintcode - sort colors II
- 测试帖子测试帖子
- 开发checklist
- 浅谈Android Fragment嵌套使用存在的一些BUG以及解决方法
- C++常考面试题:实现内存拷贝函数
- heartbeat报错 attempted replay attack
- java工程引用其他java工程解决方法
- 在Excel中对分数进行排名
- logback配置详解