1. 程式人生 > 實用技巧 >Leetcode.75 | Sort Colors

Leetcode.75 | Sort Colors

Leetcode.75 Sort Colors

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

題目相當於0、1、2排序,而且是有重複資料的排序

解法一:計數排序

class Solution:
    def sort_colors_violent(self, nums: list) -> None:
        pass

    def sort_colors_count_sort(self, nums: list) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        # 定義一個儲存空間,儲存0,1,2的頻次
        count = [0, 0, 0]
        n = len(nums)
        for i in range(n):
            count[nums[i]] += 1

        index = 0
        while count[0] > 0:
            nums[index] = 0
            index += 1
            count[0] -= 1

        while count[1] > 0:
            nums[index] = 1
            index += 1
            count[1] -= 1

        while count[2] > 0:
            nums[index] = 2
            index += 1
            count[2] -= 1

複雜度:

  • 時間複雜度:O(n+n)
  • 空間複雜度:O(k)

解法二:三路快排

由於是有重複的排序,並且只有三個數字,因此可以考慮三路快排序的partition思想

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        # [0,zero] -> 0
        # [zero+1,i] -> 1
        # [two,n-1] -> 2
        
        n = len(nums)
        zero = -1
        two = n
        i = 0
        # 注意迴圈結束條件,到two即可,由於two後邊已經排列好
        while i < two:
            if nums[i] == 0:
                zero += 1
                nums[i],nums[zero] = nums[zero],nums[i]
                i += 1
            elif nums[i] == 1:
                i += 1
            else:
                assert nums[i] == 2
                two -= 1
                nums[i],nums[two] = nums[two],nums[i]