Skip to content

Instantly share code, notes, and snippets.

@RP-3
Last active March 13, 2020 06:26
Show Gist options
  • Save RP-3/187f6a7fcb84a525d2df5bf2d58df2a5 to your computer and use it in GitHub Desktop.
Save RP-3/187f6a7fcb84a525d2df5bf2d58df2a5 to your computer and use it in GitHub Desktop.
# First naiive attempt
class Solution:
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
def sortColors(self, nums):
pl = 0
pr = len(nums)-1
while pl < pr:
if nums[pl] != 0:
self.swap(nums, pl, pr)
pr-=1
if nums[pl] == 0:
pl+=1
if nums[pl] == 0:
pl+=1
pr = len(nums)-1
while pl < pr:
if nums[pl] != 1:
self.swap(nums, pl, pr)
pr-=1
if nums[pl] == 1:
pl+=1
# After simplifying
def sortColors2(self, nums):
left = 0
right = len(nums) - 1
i = 0
while(i <= right):
if (nums[i] == 2 and i < right):
self.swap(nums, i, right)
right -= 1
elif (nums[i] == 0 and i > left):
self.swap(nums, i, left)
left += 1
else:
i+=1
# Utility methods
def swap(self, array, i, j):
tmp = array[i]
array[i] = array[j]
array[j] = tmp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment