LeetCode分类刷题之哈希表

python中的dict类型就是哈希表的原理,存储方式是key-value,通过键来快速的访问value,字典在访问操作上时间复杂度为O(1)。

1.两数之和

https://leetcode-cn.com/problems/two-sum/

解题思路:遍历一次数组,同时检查当前值缺少的那部分在不在hashmap中,如果不在就把当前的值作为key保存到hashmap

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        if not nums: return []
        #由于需要返回坐标,因此采用字典形式的hashmap
        hash_map = {}
        for i in range(len(nums)):
            t = target - nums[i]
            if t not in hash_map:
                hash_map[nums[i]] = i
            else:
                return [i, hash_map[t]]

2.判断是否存在重复元素

https://leetcode-cn.com/problems/contains-duplicate/

解题思路:遍历一次数组,将不在hashmap的元素当做key存入,这里还可以用集合set来模拟哈希表

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        if not nums: return False
        hashmap = {}
        for i in range(len(nums)):
            if nums[i] not in hashmap:
                hashmap[nums[i]] = 1
            else:
                return True
        return False

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        if not nums: return False
        if len(nums)<2:return False
        hash_map = set()
        for num in nums:
            if num not in hash_map:
                hash_map.add(num)
            else:
                return True
        return False

3.最长和谐子序列

https://leetcode-cn.com/problems/longest-harmonious-subsequence/

解题思路:通过哈希表存储每个元素出现的次数,然后遍历哈希表找到差值为1且长度最大的两个数

class Solution:
    def findLHS(self, nums: List[int]) -> int:
        if not nums: return 0

        hashmap = {}
        for i in range(len(nums)):
            if nums[i] not in hashmap:
                hashmap[nums[i]] = 1
            else:
                hashmap[nums[i]] += 1
        
        line = 0
        for i in hashmap:
            if i+1 in hashmap:
                temp = hashmap[i] + hashmap[i+1]
                if temp > line:
                    line = temp  # 用max代替
        return line

 

你可能感兴趣的:(leetcode)