75. 颜色分类https://leetcode.cn/problems/sort-colors/
题解一:
分别计算红球和白球出现的次数,nums[0:红球出现次数-1] = 0,nums[红球和白球出现次数:len(nums)] = 2
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
countRed,countWirte,countBule = 0,0,0
for i in range(len(nums)):
if(nums[i]==0):
countRed+=1
elif(nums[i]==1):
countWirte +=1
redNum = countRed
writeNum = countRed+countWirte
for i in range(len(nums)):
if(i<redNum):
nums[i] = 0
elif(i>=writeNum):
nums[i] = 2
else:
nums[i] = 1
return nums
题解二:双指针
设置start为0和1之间的边界点,end为1和2之间的边界点
nums[0:start-1] = 0 nums[start,end-1] = 1 nums[end:len(nums)] = 2
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
start,end,inx = 0,len(nums)-1,0
# [inx:end]--- 是未处理的数据:1
while(inx<=end):
if(nums[inx] == 0):
nums[start],nums[inx] = nums[inx],nums[start]
start+=1
inx += 1
elif(nums[inx]==1):
inx+=1
else:
nums[inx],nums[end] = nums[end],nums[inx]
end-=1
return nums
80. 删除有序数组中的重复项 IIhttps://leetcode.cn/problems/remove-duplicates-from-sorted-array-ii/
如果每个数出现次数最多为k次,j = k即可
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
j = 2
for i in range(2,len(nums)):
if(nums[i]!=nums[j-2]):
nums[j] = nums[i]
j+=1
return j
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
res = []
for i in range(numRows):
resRow = []
for j in range(i+1):
if(j==0 or j==i):
resRow.append(1)
else:
resRow.append(res[i-1][j-1]+res[i-1][j])
res.append(resRow)
return res
219. 存在重复元素 IIhttps://leetcode.cn/problems/contains-duplicate-ii/
用一个哈希表,维护一个k大小的集合,遍历过程中查看当前数据点是否存在集合中 ,若存在则返回True否则返回False
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
n = len(nums)
res = set()
for i in range(n):
if i>k:
res.remove(nums[i-k-1])
if nums[i] in res:
return True
res.add(nums[i])
return False
228. 汇总区间https://leetcode.cn/problems/summary-ranges/
双指针,固定i指针,j指针向后看
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
i = 0
res = []
while i<len(nums):
j = i
while j+1<len(nums) and nums[j+1]==nums[j]+1:
j+=1
if j!=i:
res.append(str(nums[i])+"->"+str(nums[j]))
i=j+1
else:
res.append(str(nums[i]))
i+=1
return res