To solve the problem, I implemented the following code:
def sortColors(nums):
low=0
mid=0
high=len(nums)-1
while(mid<=high):
if nums[mid]==0:
nums[low],nums[mid]=nums[mid],nums[low]
low=low+1
mid=mid+1
if nums[mid]==1:
mid=mid+1
if nums[mid]==2:
nums[mid],nums[high]=nums[high],nums[mid]
high=high-1
return(nums)
However, for l=[2,0,2,1,1,0], my output is [0, 0, 1, 2, 1, 2]. I don't understand the flaw in my logic.
Also if I simply replace my 3 if statements with if, elif and else, the code works perfectly fine. I am sure I am missing a Python technicality, but I am not sure what it it. Can someone please point it out?
Aucun commentaire:
Enregistrer un commentaire