Skip to content

Commit 11cd559

Browse files
Add 'Sort Colors'
1 parent 77f53db commit 11cd559

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,8 @@ A collection of LeetCode solutions
9090

9191
[Top K Frequent Elements](./src/top_k_frequent_elements.py)
9292

93+
[Sort Colors](./src/sort_colors.py)
94+
9395
[Two Sum](./src/two_sum.py)
9496

9597
[Valid Anagram](./src/valid_anagram.py)

src/sort_colors.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""
2+
75. Sort Colors
3+
4+
https://leetcode.com/problems/sort-colors
5+
6+
NOTES
7+
* Use three-way partitioning (Dutch national flag problem).
8+
"""
9+
10+
11+
class Solution:
12+
def sortColors(self, nums: list[int]) -> None:
13+
"""
14+
Do not return anything, modify nums in-place instead.
15+
"""
16+
i, j, k = 0, 0, len(nums) - 1
17+
18+
while j <= k:
19+
if nums[j] > 1:
20+
nums[j], nums[k] = nums[k], nums[j]
21+
k -= 1
22+
elif nums[j] < 1:
23+
nums[j], nums[i] = nums[i], nums[j]
24+
i += 1
25+
j += 1
26+
else:
27+
j += 1

tests/test_sort_colors.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
"""
2+
75. Sort Colors
3+
4+
https://leetcode.com/problems/sort-colors
5+
"""
6+
7+
from unittest import TestCase
8+
9+
from src.sort_colors import Solution
10+
11+
12+
class TestSolution(TestCase):
13+
def test_1(self):
14+
exp = [0, 0, 1, 1, 2, 2]
15+
nums = [2, 0, 2, 1, 1, 0]
16+
Solution().sortColors(nums)
17+
assert nums == exp
18+
19+
def test_2(self):
20+
exp = [0, 1, 2]
21+
nums = [2, 0, 1]
22+
Solution().sortColors(nums)
23+
assert nums == exp

0 commit comments

Comments
 (0)