|
| 1 | +from typing import List |
| 2 | + |
| 3 | + |
| 4 | +class Solution: |
| 5 | + """Base class for all LeetCode Problems.""" |
| 6 | + |
| 7 | + def sortColorsBS(self, nums: List[int]) -> None: |
| 8 | + """ |
| 9 | + Given an array nums with n objects colored red, white, or blue, sort them |
| 10 | + in-place so that objects of the same color are adjacent, with the colors in the |
| 11 | + order red, white, and blue. |
| 12 | +
|
| 13 | + We will use the integers 0, 1, and 2 to represent the color red, white, and |
| 14 | + blue, respectively. |
| 15 | +
|
| 16 | + You must solve this problem without using the library's sort function. |
| 17 | +
|
| 18 | + Do not return anything, modify nums in-place instead. |
| 19 | + """ |
| 20 | + # Bucket Sort Solution |
| 21 | + # Time Complexity: O(n) |
| 22 | + # Space Complexity: O(1) |
| 23 | + |
| 24 | + # Count the number of occurrences of each color |
| 25 | + count = [0, 0, 0] |
| 26 | + for i in range(len(nums)): |
| 27 | + count[nums[i]] += 1 |
| 28 | + |
| 29 | + # Fill the array with the sorted colors |
| 30 | + j = 0 |
| 31 | + for i in range(len(nums)): |
| 32 | + while j < len(count) and count[j] == 0: |
| 33 | + j += 1 |
| 34 | + nums[i] = j |
| 35 | + count[j] -= 1 |
| 36 | + |
| 37 | + def sortColorsQS(self, nums: List[int]) -> None: |
| 38 | + """ |
| 39 | + Given an array nums with n objects colored red, white, or blue, sort them |
| 40 | + in-place so that objects of the same color are adjacent, with the colors in the |
| 41 | + order red, white, and blue. |
| 42 | +
|
| 43 | + We will use the integers 0, 1, and 2 to represent the color red, white, and |
| 44 | + blue, respectively. |
| 45 | +
|
| 46 | + You must solve this problem without using the library's sort function. |
| 47 | +
|
| 48 | + Do not return anything, modify nums in-place instead. |
| 49 | + """ |
| 50 | + # (Simple) Quick Sort Solution |
| 51 | + # Time Complexity: O(n) |
| 52 | + # Space Complexity: O(1) |
| 53 | + |
| 54 | + left, right = 0, len(nums) - 1 |
| 55 | + i = 0 |
| 56 | + |
| 57 | + while i <= right: |
| 58 | + if nums[i] == 0: |
| 59 | + nums[left], nums[i] = nums[i], nums[left] |
| 60 | + left += 1 |
| 61 | + elif nums[i] == 2: |
| 62 | + nums[i], nums[right] = nums[right], nums[i] |
| 63 | + right -= 1 |
| 64 | + i -= 1 |
| 65 | + i += 1 |
0 commit comments