Sort Colors -- Python Solution -- Constant Space -- 14 lines


  • 0
    C
    class Solution(object):
    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        red, white, blue = 0, 0, 0
        for i in range(len(nums)):
            if nums[i] == 0:
                red += 1 
            elif nums[i] == 1:
                white += 1
            elif nums[i] == 2:
                blue += 1
        for h in range(red):
            nums[h] = 0
        for j in range(red, red + white):
            nums[j] = 1
        for k in range(red + white, red + white + blue):
            nums[k] = 2

Log in to reply
 

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