075 Sort Colors

075 Sort Colors

这道题最偷懒的方法当时是 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

 

posted @ 2015-07-19 14:24  dapanshe  阅读(107)  评论(0编辑  收藏  举报