給定一個包含紅色、白色和藍色,一共 n 個元素的數組,原地對它們進行排序,使得相同顏色的元素相鄰,並按照紅色、白色、藍色順序排列。
此題中,我們使用整數 0、 1 和 2 分別表示紅色、白色和藍色。
注意:
不能使用代碼庫中的排序函數來解決這道題。
示例:
輸入: [2,0,2,1,1,0] 輸出: [0,0,1,1,2,2]
進階:
- 一個直觀的解決方案是使用計數排序的兩趟掃描算法。
首先,迭代計算出0、1 和 2 元素的個數,然後按照0、1、2的排序,重寫當前數組。 - 你能想出一個僅使用常數空間的一趟掃描算法嗎?
class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
l = len(nums)
k = j = 0
while j < l:
if nums[j] == 2:
nums.pop(j)
nums.append(2)
l -= 1
elif nums[j] == 0:
nums[k], nums[j] = nums[j], nums[k]
k += 1
j += 1
else:
j += 1
#return nums
執行用時: 44 ms, 在Sort Colors的Python3提交中擊敗了99.58% 的用戶