Two python solution, not very sure if one-pass, can anyone give some comments?


  • 0
    W
    class Solution(object):
        def sortColors(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            '''
            #record 1 and 2's position
            i=0
            j=len(nums)
            p2=j-1
            p1=j-1
            while i<=p1:
                if nums[i] == 2:
                    nums[i],nums[p1]=nums[p1],nums[i]
                    nums[p2],nums[p1]=nums[p1],nums[p2]
                    p2-=1
                    p1-=1
                    continue
                if nums[i] == 1:
                    nums[i],nums[p1]=nums[p1],nums[i]
                    p1-=1
                    continue
                if nums[i] == 0:
                    i+=1
                    continue
            '''
            #record 0 and 2's position
            i=0
            j=len(nums)
            p0=0
            p2=j-1
            while i<=p2:
                if nums[i]==0:
                    nums[i],nums[p0]=nums[p0],nums[i]
                    i+=1
                    p0+=1
                    continue
                if nums[i]==2:
                    nums[i],nums[p2]=nums[p2],nums[i]
                    p2-=1
                    continue
                if nums[i] == 1:
                    i+=1
                    continue

Log in to reply
 

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