Readable Python solution [49ms]


  • 0
    class Solution(object):
        def sortColors(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            # Count the number of occurrences of each distinct value
            counters = [0, 0, 0]
            for num in nums:
                counters[num] += 1
                
            # Fill list with ordered items
            i = 0
            for num, count in enumerate(counters):
                for j in xrange(i, i+count):
                    nums[j] = num
                i += count
    

Log in to reply
 

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