LeetCode 有关哈希表的做题笔记 Python实现

有关哈希表的LeetCode做题笔记,Python实现

242. 有效的字母异位词 Valid Anagram

LeetCodeCN 第242题链接

第一种方法:对两个字符串排序后对比

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return sorted(s) == sorted(t)

第二种方法:用哈希表对字符串内每个字符计数,最后比对哈希表,这里用dict实现

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        map1, map2 = {}, {}
        for i in s:
            map1[i] = map1.get(i, 0) + 1
        for j in t:
            map2[j] = map2.get(j, 0) + 1
        return map1 == map2

1. 两数之和 Two Sum

LeetCodeCN 第1题链接

第一种方法:用哈希表,时间复杂度是O(n)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        for i in range(len(nums)):
            if nums[i] in dic:
                return [dic[nums[i]], i]
            else:            
                dic[target - nums[i]] = i

第二种方法:暴力两重遍历,这样时间复杂度是O(n^2),在LeetCode里提交会超时

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]

15. 三数之和 3Sum

LeetCodeCN 第15题链接

第一种方法:三重遍历,时间复杂度为O(n^3)

第二种方法:两重遍历得到前两个数,然后查询第三个数-(a+b)是否存在。用哈希表set()

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if len(nums) < 3:
            return []
        nums.sort()
        res = set()
        for i, v in enumerate(nums[:-2]) :
            if i >= 1 and v == nums[i-1]:
                continue
            d = {}
            for x in nums[i+1:]:
                if x not in d:
                    d[-(v+x)] = 1
                else:
                    res.add((v, -(v+x), x))
        return map(list, res)

第三种方法:先升序排序,一遍遍历,然后在后面的新数组里用双指针检查三个数之和是否为0,大于0则右指针向左走,小于0则左指针向右走。

class Solution(object):
    def threeSum(self, nums):
        if len(nums) < 3:
            return []
        nums.sort()
        res = []
        for i, x in enumerate(nums[:-2]):
            if i >= 1 and x == nums[i-1]:
                continue
            l, r = i+1, len(nums)-1
            while l < r:
                s = nums[i] + nums[l] + nums[r]
                if s < 0:
                    l += 1
                elif s > 0:
                    r -= 1
                else:
                    res.append((nums[i], nums[l], nums[r]))
                    while l < r and nums[l] == nums[l+1]:
                        l += 1
                    while l < r and nums[r] == nums[r-1]:
                        r -= 1
                    l += 1
                    r -= 1
        return res
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 18,235评论 2 36
  • 散列表概念 散列表(Hash table,也叫哈希表),是根据键(Key)而直接访问在内存存储位置的数据结构。也就...
    五分钟学算法阅读 4,411评论 1 6
  • 2019 iOS面试题大全---全方面剖析面试2018 iOS面试题---算法相关1、七种常见的数组排序算法整理(...
    Theendisthebegi阅读 11,178评论 1 6
  • 一些概念 数据结构就是研究数据的逻辑结构和物理结构以及它们之间相互关系,并对这种结构定义相应的运算,而且确保经过这...
    Winterfell_Z阅读 11,426评论 0 13
  • 有两个字典,分别存有 100 条数据和 10000 条数据,如果用一个不存在的 key 去查找数据,在哪个字典中速...
    和风细羽阅读 6,948评论 0 5

友情链接更多精彩内容