前言
由于在笔试的时候用python做DFS老是会超时,因此最近考虑同时写Python和C++,由于C++太久没写不会很熟练,所以先更新python,每周末休息日会挑之前做过的题目,每日挑一题更新C++版本(希望可以坚持)
一、有效的字母异位词
leetcode 242 有效的字母异位词
一个简单的哈希表问题
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
hashmap = {}
for i in range(len(s)):
if s[i] in hashmap.keys():
hashmap[s[i]] += 1
else:
hashmap[s[i]] = 1
if len(s) != len(t):
return False
else:
for i in range(len(t)):
if t[i] in hashmap.keys() and hashmap[t[i]] > 0:
hashmap[t[i]] -= 1
else:
return False
return True
二、两个数组的交集
leetcode 349 两个数组的交集
用一个hash表来代表元素出现的次数就可以
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
repeat = {}
for i in nums1:
if i not in repeat:
repeat[i] = 'nums1'
for i in nums2:
if i in repeat:
repeat[i] = 'repeat'
result = []
for key in repeat:
if repeat[key] == 'repeat':
result.append(key)
return result
三、快乐数
class Solution:
def isHappy(self, n: int) -> bool:
hashmap = {}
hashmap[n] = 1
while 1:
replaced = 0
while n:
replaced += (n % 10) ** 2
n = n // 10
if replaced == 1:
return True
elif replaced in hashmap.keys():
return False
else:
hashmap[replaced] = 1
n = replaced
四、两数之和
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap = collections.defaultdict(int)
n = len(nums)
for i in range(n):
if hashmap[target - nums[i]] != 0:
return [hashmap[target - nums[i]] - 1, i]
hashmap[nums[i]] += i + 1