Verbose solution in Python


  • 0
    C

    Solve by creating three subarrays for red white blue

    class Solution(object):
        def sortColors(self, nums):
            redPointer,whitePointer,bluePointer=self.getPointers(nums)
            for i in range(0,len(nums)):
                print redPointer,whitePointer,bluePointer
                num = nums[i]
                if num == 0: #red
                    redPointer = self.swapAndUpdatePointer(i, nums, redPointer)
            for i in range(redPointer,len(nums)):
                num = nums[i]
                if num == 1: #white
                    whitePointer = self.swapAndUpdatePointer(i, nums, whitePointer)
            for i in range(whitePointer, len(nums)):
                num = nums[i]
                if num == 2: #blue
                    bluePointer = self.swapAndUpdatePointer(i, nums, bluePointer)
    
        def swapAndUpdatePointer(self, i, nums, pointer):
            nums[i], nums[pointer] = nums[pointer], nums[i]
            return pointer + 1
        
        def getPointers(self, nums):
            array = [0,0,0]
            for num in nums:
                array[num]+=1
            return 0, array[0], array[0] + array[1]
    

Log in to reply
 

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