題目:第75題:給定一個包含紅色、白色和藍色,一共 n 個元素的數組,原地對它們進行排序,使得相同顏色的元素相鄰,並按照紅色、白色、藍色順序排列。 此題中,我們使用整數 0、 1 和 2 分別表示紅色、白色和藍色。 注意: 不能使用代碼庫中的排序函數來解決這道題。
思路:
思路較簡單,提示了進階思路
進階:
一個直觀的解決方案是使用計數排序的兩趟掃描算法。
首先,迭代計算出0、1 和 2 元素的個數,然后按照0、1、2的排序,重寫當前數組。
你能想出一個僅使用常數空間的一趟掃描算法嗎?
程序1:
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
if length <= 0:
return nums
if length == 1:
return nums
num_0 = 0
num_1 = 0
num_2 = 0
for index1 in range(length):
if nums[index1] == 0:
num_0 += 1
elif nums[index1] == 1:
num_1 += 1
elif nums[index1] == 2:
num_2 += 1
for index2 in range(0, num_0):
nums[index2] = 0
for index3 in range(num_0, num_0 + num_1):
nums[index3] = 1
for index4 in range(num_0 + num_1, length):
nums[index4] = 2
常數空間的方法:
這個超時了,之后的按照這個思想來改進
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
if length <= 0:
return nums
if length == 1:
return nums
index1 = 0
while index1 < length:
if nums[index1] == 0:
del nums[index1]
nums = [0] + nums
index1 += 1
elif nums[index1] == 2:
del nums[index1]
nums = nums + [2]
index1 = index1
elif nums[index1] == 1:
index1 += 1
#return nums
改進的方法:
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
num_0 = 0
num_2 = length - 1
index = 0
while index <= num_2:
if nums[index] == 0:
nums[index], nums[num_0] = nums[num_0], nums[index]
num_0 += 1
elif nums[index] == 2:
nums[index], nums[num_2] = nums[num_2], nums[index]
index -= 1
num_2 -= 1
index += 1