Scribbling

LeetCode: 75. Sort Colors 본문

Computer Science/Coding Test

LeetCode: 75. Sort Colors

focalpoint 2021. 9. 28. 21:34

We already know that all the elements are in [0, 1, 2].

So, we count each element's frequencies.

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        count = [0] * 3
        for num in nums:
            count[num] += 1
        count[2] = count[1] + count[0]
        count[1] = count[0]
        
        for i in range(count[1]):
            nums[i] = 0
        for i in range(count[1], count[2]):
            nums[i] = 1
        for i in range(count[2], len(nums)):
            nums[i] = 2

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 76. Minimum Window Substring  (0) 2021.09.30
LeetCode: 77. Combinations  (0) 2021.09.28
LeetCode: 74. Search a 2D Matrix  (0) 2021.09.28
LeetCode: 73. Set Matrix Zeroes  (0) 2021.09.28
LeetCode: 72. Edit Distance  (0) 2021.09.26