随笔-生活工作点滴

75. Sort Colors (Medium)

2019-07-07  本文已影响1人  Ysgc

Description:

Given an array with n objects colored red, white or blue, sort them **in-place **so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: You are not suppose to use the library's sort function for this problem.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Follow up:


Solution:

Solution1: inspired by "follow up" (1)

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        collection = [0,0,0]
        for n in nums:
            collection[n] += 1
            
        k = 0
        for i in range(3):
            for j in range(collection[i]):
                nums[k] = i
                k += 1

Performance:

Solution1: inspired by "follow up" (2)

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        i,j = 0,len(nums)-1
        while j > -1 and nums[j] == 2: # make sure that i 左边要么空要么都是1, j右边要么空要么都是2,k左边要么0要么1,没有2
            j -= 1# make sure ..
        while i < len(nums) and nums[i] == 0:# make sure ..
            i += 1# make sure ..
            
        k = i
        while k < j+1:
            if nums[k] == 2 and k < j: # 换回来的可能是0 or 1, 不可能是2
                nums[k],nums[j] = nums[j],nums[k]
            if nums[k] == 0 and k > i: 
# 此0可能是和j换回来的,也可能是原生的。此步换回来的只可能是1, 不可能是0 or 2。也因此判断0在判断2后面
                nums[k],nums[i] = nums[i],nums[k]
            while j > -1 and nums[j] == 2:# make sure ..
                j -= 1# make sure ..
            while i < len(nums) and nums[i] == 0:# make sure ..
                i += 1# make sure ..
            k += 1

Performance:

上一篇下一篇

猜你喜欢

热点阅读