10 lines of Python, in-place partition


  • 0
    L

    Okay, I admit the layout is ugly, but it's python ...

    from collections import Counter
    class Solution(object):
        def sortColors(self, nums):
            n=Counter(nums)
            i,bound=[0,n[0],n[0]+n[1]],(n[0],n[0]+n[1],n[0]+n[1]+n[2])
            for m in (0,1):
                while 0<=i[m]<bound[m]:
                    if nums[i[m]]==0: 
                        i[m]+=1
                    else:
                        k=nums[i[m]]
                        nums[i[k]],nums[i[m]]=nums[i[m]],nums[i[k]]
                        i[k]+=1
    

Log in to reply
 

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