LeetCode 哈希表刷题清单-Day2

0 阅读3分钟

Day 2:HashMap 基础(映射、计数)

    1. 两数之和
    1. 有效的字母异位词
    1. 字符串中的第一个唯一字符
    1. 两个数组的交集 II

1. 两数之和

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。 你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。

这个题真的是常做常新,每次都有新的思考。最新的理解是这是一个查找题。 从历史数据中查找想要的数据,这就是hash查找题的本质

我们先将所有的数据都存储到hashset中,然后开始遍历数组,对于某个数v,想要知道数组中是否存在一个数u,使得u+v=target,那么其实就是查找数组中是否存在u=target-v,如果u存在,则满足两数之和为target

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        pos={}
        for i, v in enumerate(nums):
            u = target - v
            if u in pos:
                return i,pos[u]
            else:
                pos[v] = i

242. 有效的字母异位词

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的 字母异位词。

统计两个字符串中每个字符的出现次数是否完全一致。我们统计出t的中字符和数量,然后再统计出s中的字符和每个字符的数量,进行比较即可

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        table = {}
        for c in s:
            if c in table:
                table[c] += 1
            else:
                table[c] = 1
        
        for c in t:
            if c in table:
                table[c] -= 1
            else:
                return False
        
        for k,v in table.items():
            if v != 0:
                return False
        return True

387. 字符串中的第一个唯一字符

给定一个字符串 s ,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1 。

统计所有字符出现的次数,然后遍历得到首次出现的字符

class Solution:
    def firstUniqChar(self, s: str) -> int:
        table={}
        for c in s:
            if c in table:
                table[c] += 1
            else:
                table[c] = 1
        
        for i, c in enumerate(s):
            if table[c] == 1:
                return i
        return -1

只出现一次的字符,左边查找的位置和右边查找的位置相等

示例1 遍历所有字符,如果没有出现则为-1

class Solution(object):
    def firstUniqChar(self, s: str) -> int:
        min_unique_char_index = len(s)
        for c in "abcdefghijklmnopqrstuvwxyz":
            i = s.find(c)
            if i != -1 and i == s.rfind(c):
                min_unique_char_index = min(min_unique_char_index, i)
        return min_unique_char_index if min_unique_char_index != len(s) else -1

示例2,只遍历已存在的字符,因此不会出现-1的情况

class Solution:
    def firstUniqChar(self, s: str) -> int:
        loc = len(s) 
        for w in set(s):  
            if s.find(w) == s.rfind(w):  
                loc = min(loc, s.find(w))
        return loc if loc != len(s) else -1

350. 两个数组的交集 II

给你两个整数数组 nums1 和 nums2 ,请你以数组形式返回两数组的交集。返回结果中每个元素出现的次数,应与元素在两个数组中都出现的次数一致(如果出现次数不一致,则考虑取较小值)。可以不考虑输出结果的顺序。

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nums1 = Counter(nums1)
        nums2 = Counter(nums2)

        num = nums1 & nums2

        return list(num.elements())