题目来源:
https://leetcode.com/problems/sort-colors/
题意分析:
给定n个颜色,红色,白色和蓝色。分别用0,1,2代替,将这些颜色排序,0在1前,1在2前。
题目思路:
记录一下起始位置和末尾。遍历一下输入,如果是2就放到末尾,末尾-1,如果是0,那么放到开始位置,其实位置+1.
代码(Python):
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
转载请注明出处:http://www.cnblogs.com/chruny/p/5069860.html