算法篇之(Map & Set)

前言:前面学习了List线性表的数组、链表数据结构,本篇博客主要学习和List相似的数据结构:Map和Set。

目录

思维导图

有效字母异位词

两数之和


思维导图

有效字母异位词

可以用哈希表实现

先创建哈希表, dic1={}对每个字符串进行遍历,for item in s: 

如果遍历出的字母在哈希表里不存在,则在哈希表里添加key,默认值是+1;如果遍历出的字母在哈希表里存在,则在原始的key对应的值上加1,dic1[item] = dic1.get(item,0)+1

最后比较两个表的key和value是否相等,相等返回true,不相等返回false,return dic1 == dic2

关键代码:dic1[item] = dic1.get(item,0)+1

这行代码作用就是先找到key,找到对应的value加+1,找不到,添加进入,然后value值+1

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        dic1={}
        dic2={}
        for item in s:
            dic1[item] = dic1.get(item,0)+1
        for item in t:
            dic2[item] = dic2.get(item,0)+1
        return dic1 == dic2

两数之和

用两层for循环,时间复杂度O(n^2)

第一层for循环,取出数组里的下标和对应的值,for index,value in enumerate(nums):

第二层for循环,在第一层循环取到的下标基础上,取出数组里后面的数所对应的下标,for j in range(index+1,len(nums)):,举例:nums=[2,3,5,6,8],当第一层循环拿出下标0,值2时,第二层循环拿出下标1,值3,....,下标4,值8

进行判断,两次拿出的数等于目标值,则返回对应的下标, if value+nums[j] == target:

需要注意的点:

第2层循环取下标和值时,不包括第一层循环取出来的数,用的是index+1

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for index,value in enumerate(nums):
            for j in range(index+1,len(nums)):
                if value+nums[j] == target:
                    return [index,j]

用哈希表实现,时间复杂度O(n)

先创建一个空的哈希表,hash_map = {}

取出数组里的下标和值,for index,value in enumerate(nums):

将取出的下标和值放进哈希表中,hash_map[value] = index,举例:nums=[2,3,5,6,8],hash_map = {2:0,3:1,5:2,6:3,8:4}

在哈希表中找值,如果目标值减去取出的值所在的值不为空,返回此值和取出值所在的索引,举例,如果目标值是8,当for循环取到3这个值时,去哈希表中找8-5这个key所在的value,如果有,就返回其value,也就是2,同时也返回3这个值所在的下标值1,if hash_map.get(target-value) is not None: return(hash_map.get(target-value),index)

需要注意的点,在往哈希表里存放时,用的是hash_map[value] = index,值作为key,下标作为value,从哈希表里找值时,用的是hash_map.get(target-value),找到的是key,通过key,找value也是下标值。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hash_map = {}
        for index,value in enumerate(nums):
            if hash_map.get(target-value) is not None:
                return(hash_map.get(target-value),index)
            hash_map[value] = index
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MRJJ_9

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值