Sort Colors
LeetCode 75 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
low / mid / high pointers partition into 0s, 1s, 2s in one pass.
நான் Sort Colors (LeetCode 75) ஐ இப்படித் தீர்த்தேன் — Two Pointers பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Dutch national flag: keep three regions — 0s on the left of low, 2s on the right of high, and 1s in between. mid scans the unknown part and sends 0s left and 2s right with swaps.
Approach
- 1
0 at mid: swap with low, advance both.
- 2
1 at mid: just advance mid.
- 3
2 at mid: swap with high and shrink high (don't advance mid — the swapped-in value is unchecked).
நான் எப்படித் தீர்த்தேன்
Dutch national flagPythonO(n) time · O(1) space
class Solution:
def sortColors(self, nums: list[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
low=0
mid = 0
high = len(nums)-1
while mid<=high:
if nums[mid]==0:
#move left
nums[low],nums[mid]=nums[mid],nums[low]
#increase right boundary of 0
low+=1
mid+=1
elif nums[mid]==1:
#no worries
mid+=1
elif nums[mid]==2:
nums[mid],nums[high]=nums[high],nums[mid]
#increase the left boundary of 2
high-=1
Sort Colors — அடிக்கடி கேட்கப்படும் கேள்விகள்
Sort Colors பின்னாலுள்ள intuition என்ன?
Dutch national flag: keep three regions — 0s on the left of low, 2s on the right of high, and 1s in between. mid scans the unknown part and sends 0s left and 2s right with swaps.
Sort Colors (LeetCode 75) ஐ எப்படித் தீர்ப்பது?
1. 0 at mid: swap with low, advance both. 2. 1 at mid: just advance mid. 3. 2 at mid: swap with high and shrink high (don't advance mid — the swapped-in value is unchecked).
Sort Colors இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(1). (Accepted approach: Dutch national flag.)
Sort Colors இல் பொதுவான தவறுகள் என்ன?
Don't increment mid after swapping with high.