Description:
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
Example:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Input: nums = [2,0,1]
Output: [0,1,2]
Ideas:
I think of using pointers when it involves traversing list.The left pointer and i are Swapped when
meet 0, do the same to right pointers and i when meet 2.The loop is Finished while i>r.
Code:
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
l, r = 0, len(nums)-1
i = 0
while i<=r:
if nums[i] == 0:
nums[i], nums[l] = nums[l], nums[i]
l += 1
if i < l:
i=l
elif nums[i] == 2:
nums[i], nums[r] = nums[r], nums[i]
r -= 1
else:
i+=1
return nums
Execution times:16 ms
Memory consumption:12.8 MB
Summary
Grades: Only one pass through medium question and two pass through easy question, calling sort entry question.