排颜色 II
来源:互联网 发布:js 一切皆对象 编辑:程序博客网 时间:2024/06/05 03:08
题目描述:给定一个有n个对象(包括k种不同的颜色,并按照1到k进行编号)的数组,将对象进行分类使相同颜色的对象相邻,并按照1,2,...k的顺序进行排序。
样例:给出colors=[3, 2, 2, 1, 4],k=4, 你的代码应该在原地操作使得数组变成[1, 2, 2, 3, 4]
与上一道颜色排列的问题(详见:点击打开链接)不同之处在于现在有多个元素,所以直接进行快速排序即可,是有重复元素的快速排序。(这里,我实在觉得此处给的参数k没什么大用,如果谁有比我给的更好的方法,用到k了,请不吝赐教)
快速排序的方法之前详细讨论过了(点击打开链接),不再赘述,直接给出代码:
class Solution: """ @param colors: A list of integer @param k: An integer @return: nothing """ def sortColors2(self, colors, k): if k == 1 or len(colors) == 0: return colors end = len(colors) - 1 begin = 0 self.helper(colors, begin, end) return colors def helper(self, colors, begin, end): if begin >= end: return pivot = colors[begin] index = begin for cur in range(begin + 1, end + 1): if colors[cur] <= pivot: index += 1 colors[cur], colors[index] = colors[index], colors[cur] colors[begin], colors[index] = colors[index], colors[begin] self.helper(colors, begin, index - 1) self.helper(colors, index + 1, end) # write your code here其中,helper函数是快排,用begin和end代表首尾位置,这种形参设置的方法之前已经说过很多
0 0
- 排颜色 II
- LintCode : 排颜色 II
- LintCode:排颜色 II
- 排颜色 II
- lintcode ----排颜色 II
- 排颜色 II -LintCode
- lintcode-排颜色II-143
- lintcode(143)排颜色 II
- Java实现-排颜色ii
- 143.Sort Colors II-排颜色 II(中等题)
- 九章算法面试题70 排颜色II sort colors
- 网线的颜色怎么排?
- TextView的图文混排,不同文字颜色混排
- SpannableString设置AndroidTextView改变颜色,文字大小,图文混排等等
- 九章算法面试题69 排颜色 sort colors
- 排颜色问题——数组 leetcode lintcode
- android TextView部分字体颜色设置以及图文混排
- NSMutableAttributedString,图文混排,字号变换,颜色变换
- python初学者常见问题汇总(留作日后参考)
- 备份Foxmail7.2邮箱
- HDU-4587 TWO NODES (割点[Tarjan])
- 2.oracle的dump理解二 Buffer Header和Block Header
- 通过applicationContext文件配置项目首页,<mvc:view-controller...>
- 排颜色 II
- C++游戏内进程条
- Django基本命令
- zoj 3944 暴力 People Counting
- VS2010 MFC 读取Excel(2)
- GDOI2016模拟1总结
- Leetcode Symmetric Tree 101
- IOS设计模式之外观模式
- Android中的Environment.getExternalStorageState使用