Leetcode # 75 (Python): Sort Colors

정욱·2021년 4월 23일
0

Leetcode

목록 보기
24/38

Sort Colors

  • Difficulty: Medium
  • Type: Sorting
  • link

Problem

Solution

  • Dutch National Flag Problem (Three Pointers)
  • Time complexity: O(n)
class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        # mid value equals 1 in this problem
        start = 0
        cur = 0
        end = len(nums)

        while cur < end:
            # Swap with the start pointer when value in current pointer is smaller than mid
            if nums[cur] < 1:
                nums[start], nums[cur] = nums[cur], nums[start]
                start += 1
                cur += 1
            # Swap with the end pointer when value in current pointer is bigger than mid
            elif nums[cur] > 1: # mid
                end -= 1
                nums[cur], nums[end] = nums[end], nums[cur]
            # Do not swap but increase current pointer by 1 if value in cur pointer = mid
            else:
                cur += 1

1개의 댓글

comment-user-thumbnail
2021년 12월 23일

It is a best solution found that very popular and helpful:
https://www.youtube.com/watch?v=HmRWI_ypnM4&ab_channel=EricProgramming

답글 달기