sort 0,1,2 - O(n) python


  • 0
    S
    class Solution(object):
        def sortColors(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            # l = left
            # r = right
            l,i,r = 0, 0, len(nums)-1
            
            while l < len(nums) and nums[l] == 0:
                l += 1
            
            i = l
            
            while r > -1 and nums[r] == 2:
                r -= 1
                
            while i <= r:
                if nums[i] == 0:
                    nums[l], nums[i] = nums[i], nums[l]
                    while l < len(nums) and nums[l] == 0:
                        l += 1
                    i = l
                    if i > r:
                        break
    
                if nums[i] == 2:
                    nums[r], nums[i] = nums[i], nums[r]
                    while r > -1 and nums[r] == 2:
                        r -= 1
    
                if nums[i] == 1:
                    i += 1
    
                    
                    
                    
                    
                    
                    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.