203.移除链表元素
题目链接:力扣242
思路:哈希表
ord()用于求ASCII码
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
hashmap = [0]*26
for i in s:
hashmap[ord(i) - ord('a')] += 1
for i in t:
hashmap[ord(i) - ord('a')] -= 1
for i in hashmap:
if i != 0:
return False
return True
349. 两个数组的交集
题目链接:力扣349
思路:哈希表
注意这里因为数字数量不确定,不能简单的采用数组(列表)作为哈希表。
上一题可以用是因为字母只有26个,能直接用下标表示字母,数组大小也仅仅为26,但若数字有成千上万个,开辟大小为上万的数组不现实。
这里用字典代替set,当遇见某数时,将key设置为该数,value设置为1,之后重复该操作(若遇见之前重复的数等于什么都没做,所以该操作相当于去重)。
当需要检测时,使用hashmap.keys()方法返回字典里所有key,检测需要查找的数是否在此列表即可。
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
hashmap = {}
ans = []
for i in nums1:
hashmap[i] = 1 # key设置为该数,value设置为1
for j in nums2:
if j in hashmap.keys() and hashmap[j] == 1:
ans.append(j)
hashmap[j] = 0
return ans
202. 快乐数
题目链接:力扣202
思路:哈希表
若遇见之前求过的sum,说明陷入死循环,直接返回False。
class Solution:
def isHappy(self, n: int) -> bool:
hashmap = {}
def calculate(n):
sum = 0
while n > 0:
sum += pow((n%10), 2)
n = int(n/10)
return sum
while True:
if n in hashmap.keys():
return False
elif calculate(n) == 1:
return True
else:
hashmap[n] = 1
n = calculate(n)
1. 两数之和
题目链接:力扣1
思路:哈希表
用key存储数组值,用value存储下标,因为最后需要用值去字典中寻找下标。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
record = {}
for i in range(len(nums)):
if (target-nums[i]) in record.keys():
return [i, record[target-nums[i]]]
else:
record[nums[i]] = i