[LeetCode]题解(python):075-Sort Colors
2015-12-23 14:27
525 查看
[b]题目来源:[/b]
https://leetcode.com/problems/sort-colors/
[b]题意分析:[/b]
给定n个颜色,红色,白色和蓝色。分别用0,1,2代替,将这些颜色排序,0在1前,1在2前。
[b]题目思路:[/b]
记录一下起始位置和末尾。遍历一下输入,如果是2就放到末尾,末尾-1,如果是0,那么放到开始位置,其实位置+1.
[b]代码(Python):[/b]
View Code
转载请注明出处:http://www.cnblogs.com/chruny/p/5069860.html
https://leetcode.com/problems/sort-colors/
[b]题意分析:[/b]
给定n个颜色,红色,白色和蓝色。分别用0,1,2代替,将这些颜色排序,0在1前,1在2前。
[b]题目思路:[/b]
记录一下起始位置和末尾。遍历一下输入,如果是2就放到末尾,末尾-1,如果是0,那么放到开始位置,其实位置+1.
[b]代码(Python):[/b]
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ i,start,end = 0,0,len(nums) - 1 while i <= end: if nums[i] == 2: nums[i],nums[end] = nums[end],nums[i] end -= 1 elif nums[i] == 0: nums[i],nums[start] = nums[start],nums[i] start += 1 i += 1 else: i += 1
View Code
转载请注明出处:http://www.cnblogs.com/chruny/p/5069860.html
相关文章推荐
- 每天学点Python之strings
- 每天学点Python之comprehensions
- Python模块
- Python基础教程 第11章: 文件和流 学习笔记
- 学好 Python 的 11 个优秀资源
- Python进阶09 动态类型
- [LeetCode]题解(python):074-Search a 2D Matrix
- Python进阶08 异常处理
- Python进阶07 函数对象
- Python进阶06 循环对象
- Python进阶05 循环设计
- Python进阶04 函数的参数对应
- Python进阶03 模块
- Python进阶02 文本文件的输入输出
- Python进阶01 词典
- [LeetCode]题解(python):073-Set Matrix Zeroes
- python timeit
- python datetime strftime格式变换
- [LeetCode]题解(python):072-Edit Distance
- writing idiomatic python 读书笔记(1)