LeetCode|アルゴリズムLeetCode|アルゴリズム:カラーソート

1779 ワード

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. メモ:This is a dutch partitioning problem.We are classifying the array into four groups: red, white, unclassified, and blue. Initially we group all elements into unclassified. We iterate from the beginning as long as the white pointer is less than the blue pointer.
  • If the white pointer is red (nums[white] == 0), we swap with the red pointer and move both white and red pointer forward.
  • If the pointer is white (nums[white] == 1), the element is already in correct place, so we don't have to swap, just move the white pointer forward.
  • If the white pointer is blue, we swap with the latest unclassified element.
  • class Solution:
        def sortColors(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            if len(nums) <= 1: 
                return
            max_zero_index = 0
            min_two_index = len(nums) - 1
            
            i = 0
            while i <= min_two_index:
                if nums[i] == 0:
                    nums[i], nums[max_zero_index] = nums[max_zero_index], nums[i]
                    max_zero_index += 1
                    i += 1
                elif nums[i] == 1:
                    i += 1
                else:
                    nums[i], nums[min_two_index] = nums[min_two_index], nums[i]
                    min_two_index -= 1