哈希

1. 1. 两数之和

一个简单的hash,看target-n在不在hash表里就行。

需要注意的是返回应该是targrt-n和当前的坐标,防止数字重复利用

1
2
3
4
5
6
7
8
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
h = dict()
for i in range(len(nums)):
n = nums[i]
if target - n in h:
return h[target-n], i
h[n] = i

2. 49. 字母异位词分组

hash,元素需要先单独拉出来,list后排序再通过**’’.join的形式**来确定key

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
h = dict()
for s in strs:
s_list = list(s)
s_list.sort()
ss = ''.join(s_list)

if ss not in h:
h[ss] = list()
h[ss].append(s)

ans = []
for key in h:
ans.append(h[key])

return ans

3. 128. 最长连续序列

哈希集合,具体表现为set()函数

只需要看序列头开始,这个序列多长就行,所以需要一个n-1判断是不是序列头,n+1循环看长度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums = set(nums)
ans = 0
for n in nums:
if n - 1 not in nums:
max_length = 1
curr = n
while curr + 1 in nums:
max_length += 1
curr += 1
ans = max(ans, max_length)

return ans

站内搜索

没有找到内容!