If we set two pointers, p0 and p2 to indicate the supposed position of 0 and 2, the left 1 will be in the middle automatically.
Solution:
# T:O(n) S:O(1)
class Solution:
# @param {integer[]} nums
# @return {void} Do not return anything, modify nums in-place instead.
def sortColors(self, nums):
L = len(nums)
p0, p2, i = 0, L - 1, 0
while i <= p2:
if nums[i] == 2:
nums[i], nums[p2] = nums[p2], nums[i]
p2 -= 1
elif nums[i] == 0:
nums[i], nums[p0] = nums[p0], nums[i]
p0 += 1
i += 1
else:
i += 1
Run Time: 56 ms
No comments:
Post a Comment