标签:
这道题最偷懒的方法当时是 counting sort. 但是显然这道题不是考这个, 而且那样需要扫描2便。 真正的解法是 one scan, 设置一头一尾 加上 Current一共三个指针进行 swap
class Solution: # @param {integer[]} nums # @return {void} Do not return anything, modify nums in-place instead. def sortColors(self, nums): start, end = 0, len(nums) - 1 while start < len(nums) and nums[start] == 0: start += 1 k = start while start < end: while end > start and nums[end] == 2: end -= 1 while start < end and nums[start] == 0: start += 1 if k > end: break if nums[k] == 2: nums[k], nums[end] = nums[end], nums[k] end -= 1 elif nums[k] == 0: nums[k], nums[start] = nums[start], nums[k] start += 1 else: k += 1
标签:
原文地址:http://www.cnblogs.com/dapanshe/p/4658596.html