力扣Hot 100题解技巧详解:Python版
一、136. 只出现一次的数字
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return reduce(xor, nums)
二、169. 多数元素
class Solution:
def majorityElement(self, nums: List[int]) -> int:
n = len(nums)
value_counts = defaultdict(int)
for i in nums:
value_counts[i] += 1
for i in value_counts:
if value_counts[i] >= n/2:
return i
三、75. 颜色分类
两次遍历,第一次将所有的0归为,第二次将所有的1归为
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def swap(i, j):
nums[i], nums[j] = nums[j], nums[i]
n = len(nums)
ptr = 0
for i in range(n):
if nums[i] == 0:
swap(i, ptr)
ptr += 1
for i in range(n):
if nums[i] == 1:
swap(i, ptr)
ptr += 1
四、31. 下一个排列
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
i = n-2
while i >= 0 and nums[i] >= nums[i+1]:
i -= 1
if i >= 0:
j = n-1
while nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
left, right = i+1, n-1
while left<right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
五、287. 寻找重复数
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
n, i = len(nums), 0
while i < n:
t, idx = nums[i], nums[i] - 1 # t 是当前值,idx 是当前值该放到的位置
if nums[idx] == t: # 如果当前值已经在它该在的位置上
if idx != i: # 表示当前值 t 和它“应该在的位置”的值相等,说明有重复,立即返回
return t
i += 1
else:
nums[i], nums[idx] = nums[idx], nums[i]
return -1
作者:Y1nhl