[LeetCode]题解(python):075-Sort Colors

题目来源:

  https://leetcode.com/problems/sort-colors/


题意分析:

  给定n个颜色,红色,白色和蓝色。分别用0,1,2代替,将这些颜色排序,0在1前,1在2前。


题目思路:

  记录一下起始位置和末尾。遍历一下输入,如果是2就放到末尾,末尾-1,如果是0,那么放到开始位置,其实位置+1.


代码(Python):

  

 1 class Solution(object):
 2     def sortColors(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: void Do not return anything, modify nums in-place instead.
 6         """
 7         i,start,end = 0,0,len(nums) - 1
 8         while i <= end:
 9             if nums[i] == 2:
10                 nums[i],nums[end] = nums[end],nums[i]
11                 end -= 1
12             elif nums[i] == 0:
13                 nums[i],nums[start] = nums[start],nums[i]
14                 start += 1
15                 i += 1
16             else:
17                 i += 1
View Code

转载请注明出处:http://www.cnblogs.com/chruny/p/5069860.html

原文地址:https://www.cnblogs.com/chruny/p/5069860.html