0
点赞
收藏
分享

微信扫一扫

LeetCode刷题——75. 颜色分类


题目

LeetCode刷题——75. 颜色分类_数组

解法一

不就是排序吗,这是我见过最简单的题目哈哈。

class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
return nums.sort()

LeetCode刷题——75. 颜色分类_数组_02


结果还不错,平常碰到这种结果就会去刷下一题了。但是…

LeetCode刷题——75. 颜色分类_快速排序_03


LeetCode刷题——75. 颜色分类_三路快排_04

LeetCode刷题——75. 颜色分类_快速排序_05


注意这两句话,如果面试官问你这个题目,肯定不是考察是否知道库函数的使用。

解法二

由于本题元素种类非常有限,只有三种。因此,我们可以统计每种元素出现的次数,然后再放回原数组即可。

class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
count = {0:0,1:0,2:0}

for i in nums:
count[i] = count[i] + 1

index = 0
for i in range(3):
for j in range(count[i]):
nums[index] = i
index += 1

return

LeetCode刷题——75. 颜色分类_数组_06


( ⊙ o ⊙ ),这种方法看来可以,能达到和库函数类似的结果也不错了。再仔细看一下题目,三种元素。

解法三

LeetCode刷题——75. 颜色分类_数组_07


LeetCode刷题——75. 颜色分类_数组_08

记不记得有一种以三开头的排序方法?

LeetCode刷题——75. 颜色分类_库函数_09


没错,正是三路快速排序法。

class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
def swap(i,j):
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp

n = len(nums)
left = 0 # 最终保证nums[0...left] 都是0
right = n - 1 # 保证nums[right...n-1] 都是2
# 剩下的 nums[left+1...right-1] 都是1

i = 0
while i <= right:
# 1是中间
if nums[i] == 1:
i += 1
elif nums[i] > 1:
swap(right,i)
right -= 1
else: # < 1
swap(left,i)
i += 1
left += 1

return

LeetCode刷题——75. 颜色分类_快速排序_10


刷到这个结果就很欣慰了。


举报

相关推荐

0 条评论