75. Sort Colors (Medium)

作者: Ysgc | 来源:发表于2019-07-07 13:39 被阅读1次

    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:

    • A rather straight forward solution is a two-pass algorithm using counting sort.
      First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
    • Could you come up with a one-pass algorithm using only constant space?

    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:

    • Runtime: 32 ms, faster than 94.53% of Python3 online submissions for Sort Colors.
    • Memory Usage: 13.3 MB, less than 6.75% of Python3 online submissions for Sort Colors.

    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:

    • Runtime: 32 ms, faster than 94.53% of Python3 online submissions for Sort Colors.
    • Memory Usage: 13.1 MB, less than 69.19% of Python3 online submissions for Sort Colors.

    相关文章

      网友评论

        本文标题:75. Sort Colors (Medium)

        本文链接:https://www.haomeiwen.com/subject/ngebhctx.html