【个人刷题记录】因为鼠鼠还在实习,所以基本一天4题左右。两题错题+两题新题,我真的不想刷了就忘了😭
每写完一个板块就会记录一下(未来二刷三刷如果有新的体会都会更新),自我监督,让自己刷的有动力~大家一起加油🎉
1. 哈希
1.1 两数之和
两种方法解决,暴力 or 字典
python
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# 暴力法
# i=0
# j=1
# length=len(nums)
# for i in range(length):
# for j in range(i+1,length):
# res=nums[i]+nums[j]
# if res==target:
# return [i,j]
# 字典法
pool={}
length=len(nums)
for i in range(length):
derta=target-nums[i]
goal=pool.get(derta,None)
if goal!=None:
return [i,goal]
pool[nums[i]]=i
1.2 字母异位词分组
语法沉淀:
str(sorted(str)):排序str的不二选择list(dic.values()):直接返回字典的value列表target not in dic:直接查找是否存在字典中对应的key
python
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
pool={} # str-list
for item in strs:
sorted_str=str(sorted(item))
if sorted_str not in pool:
pool[sorted_str]=[item]
else:
pool[sorted_str].append(item)
return list(pool.values())
下面这种方法也可以学学:
collections.defualtdict(list):直接定义value的类型,这样就不用if-else分情况讨论了,直接添加就行
python
from collections import defaultdict
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
dic=defaultdict(list)
for s in strs:
key=str(sorted(s))
dic[key].append(s)
return list(dic.values())
1.3 最长连续序列
解法1:排序后双指针
语法沉淀:
set:无法索引。想要解决,可以转为listsorted():才能返回一个新的列表。.sort()是原地排序,无法转为新的列表
python
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 解法1:排序后遍历验证
nums_set=set(nums)
sorted_nums=sorted(list(nums_set))
max_len=0
length=len(sorted_nums)
l=0
r=0
while l < length:
cur=sorted_nums[l]
r=l+1
while r<length and sorted_nums[r]==cur+1:
cur+=1
r+=1
max_len=max(max_len,r-l)
l=r
return max_len
解法2:集合(底层使用哈希实现)
这里的妙点在于 找到最小 往后推进
python
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 从最小的出发,查看累加值是否在集合中
# set 底层 是哈希
s=set(nums)
max_len=0
for item in s:
if item-1 not in s:
x=item
while x+1 in s:
x+=1
max_len=max(max_len,x-item+1)
return max_len