1、有效的字母异位词
算是哈希表的入门吧,比较简单
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t): return False
hash_s = [0]*26
for i in range(len(s)):
hash_s[ord(s[i])-97] += 1
for i in range(len(t)):
hash_s[ord(t[i])-97] -= 1
for i in hash_s:
if i != 0:
return False
return True
2、两个数组的交集
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
hash1 = [0]*1001
hash2 = [0]*1001
result = []
for i in range(len(nums1)):
hash1[nums1[i]] = 1
for i in range(len(nums2)):
hash2[nums2[i]] = 1
for i in range(1001):
if hash1[i] and hash2[i]:
result.append(i)
return result
3、快乐数
这道题最主要就是:当计算快乐数时结果重复出现的时候肯定就进死循环了
class Solution:
def isHappy(self, n: int) -> bool:
result_list = []
while True:
count = 0
while n > 0:
a = n%10
n = n//10
count += a*a
if count == 1:
return True
elif count in result_list:
return False
else:
result_list.append(count)
n = count
4、两数之和
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_to_index = {}
for i in range(len(nums)):
rest = target - nums[i]
if rest in num_to_index:
return [num_to_index[rest], i]
num_to_index[nums[i]] = i
return []