Advertisement
smj007

Sort colors (dutch national flag problem)

Apr 19th, 2025
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. """
  2. Bucket sort: TC is O(n).
  3. There's this case nums[curr]==2, after swapping with right, we should not increase i since the number swapped back from p2 can be 0/1, which needs to be further processed
  4.  
  5. When curr pointer has passed left pointer, the number swapped from left can only be
  6. 1 as curr pointer has passeed left.
  7.  
  8. Both of them are tricky to understadn
  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.  
  17.         left = 0
  18.         right = len(nums)-1
  19.         i = 0
  20.  
  21.         while i <= right:
  22.             if nums[i] == 0:
  23.                 nums[i], nums[left] = nums[left], nums[i]
  24.                 left += 1
  25.             elif nums[i] == 2:
  26.                 nums[i], nums[right] = nums[right], nums[i]
  27.                 right -= 1
  28.                 i -= 1
  29.             i += 1
  30.  
  31.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement