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.