leetcode75. Sort Colors python代码版
程序员文章站
2024-02-23 19:48:04
...
方法一:
采用三个变量分别计数0,1,2所出现的次数。然后将0,1,2按照这个次数重新填入原列表。
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
c0 = 0
c1 = 0
c2 = 0
for num in nums:
if num == 0:
c0 += 1
if num == 1:
c1 += 1
if num == 2:
c2 += 1
i = 0
while c0 > 0:
nums[i] = 0
c0 -= 1
i += 1
while c1 > 0:
nums[i] = 1
c1 -= 1
i += 1
while c2 > 0:
nums[i] = 2
c2 -= 1
i += 1
方法二:
采用前后两头约束的方式来约束游标i,当置换过前后的约束点后,对约束点进行更新。
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zero, second = 0, len(nums)-1
i = 0
while i <= second:
while nums[i]==2 and i < second:
nums[i], nums[second] = nums[second], nums[i]
second -= 1
while nums[i]==0 and i > zero:
nums[i], nums[zero] = nums[zero], nums[i]
zero += 1
i += 1
上一篇: Java实现的mysql事务处理操作示例
下一篇: Java中Class类的作用与深入理解