代码随想录算法训练营Day6|哈希1

242.有效的字母异位词[简单题]

  • 数组模拟26个字母的哈希
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        dicts = [0]*26
        for i in s:
            dicts[ord(i)-97] += 1
        for i in t:
            dicts[ord(i)-97] -= 1
        for i in range(26):
            if dicts[i]!=0:
                return False
        return True

349. 两个数组的交集[简单题]

  • 字典dict和集合set 可以实现哈希
# 字典哈希
class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nums1_dict = {}
        res = []
        for i in nums1:
            nums1_dict[i] = 1
        
        for i in nums2:
            if i in nums1_dict.keys() and nums1_dict[i]==1:
                res.append(i)
                nums1_dict[i] = 0
        return res
# 集合哈希
class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return list(set(nums1)&set(nums2))

1.两数之和[简单题]

  • 思路一,暴力解
  • 思路二,哈希存储被减数
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        remain = {}
        for ind,i in enumerate(nums):
            if target-i in remain.keys():
                return [remain[target-i],ind]
            else:
                remain[i] = ind
        return None

你可能感兴趣的:(力扣刷题,算法,哈希算法)