知识点
-
当我们遇到了要快速判断一个元素是否出现集合里的时候,就要考虑哈希表
-
哈希表也是 牺牲了空间换取了时间,因为我们要使用额外的数组,set或者是map来存放数据,才能实现快速的查找
242. Valid Anagram
- ord()函数:返回字母对应的ASCII数字
- Python中的defaultdict方法的使用
class Solution:
def isAnagram(self, s, t):
record = [0] * 26
for i in range(len(s)):
#并不需要记住字符a的ASCII,只要求出一个相对数值就可以了
record[ord(s[i]) - ord("a")] += 1
# print(record)
for i in range(len(t)):
record[ord(t[i]) - ord("a")] -= 1
for i in range(26):
if record[i] != 0:
#record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。
return False
return True
class Solution:
def isAnagram(self, s, t):
from collections import defaultdict
s_dict = defaultdict(int)
t_dict = defaultdict(int)
for x in s:
s_dict[x] += 1
for x in t:
t_dict[x] += 1
return s_dict == t_dict
class Solution:
def isAnagram(self, s, t):
from collections import defaultdict
s_dict = {}
t_dict = {}
for x in s:
if x not in s_dict:
s_dict[x] = 1
else:
s_dict[x] += 1
for x in t:
if x not in t_dict:
t_dict[x] = 1
else:
t_dict[x] += 1
return s_dict == t_dict
349. Intersection of Two Arrays
class Solution:
def set_intersection(self, set1, set2):
return [x for x in set1 if x in set2]
def intersection(self, nums1, nums2):
x = set(nums1)
y = set(nums2)
if len(x) < len(y):
res = self.set_intersection(x, y)
return res
else:
res = self.set_intersection(y, x)
return res
class Solution:
def intersection(self, nums1, nums2):
set1 = set(nums1)
set2 = set(nums2)
return list(set2 & set1)
202. Happy Number
- 平方和计算:使用while与divmod可以计算每一位数的平方和
class Solution:
def isHappy(self, n):
def get_next(n):
total_sum = 0
while n > 0: # 当n的位数大于2的时候,每一位数字都能得到平方和计算
n, digit = divmod(n, 10) # 返回n除以10的商(n)和余数(digit)
# print(n, digit)
total_sum += digit ** 2
return total_sum
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = get_next(n)
return n == 1
1. Two Sum
class Solution:
def twoSum(self, nums, target):
hashSet = {}
for i in range(len(nums)):
hashSet[nums[i]] = i
for i in range(len(nums)):
tmp = target - nums[i]
if tmp in hashSet and hashSet[tmp] != i:
return [i, hashSet[tmp]]