代码随想录训练营第6天|哈希

题目链接:242.有效的字母异位词

思路:首先判断两个字符串长度是否相等,不相等直接False;

利用哈希表记录其中一个字符串中每个字母出现的次数,再用循环判断第二个字符串中的字母是否在哈希表中,若存在,哈希表中该字母次数减1,直到循环结束,若哈希表不为空,则失败

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        dict={}
        if len(s)!=len(t):
            return False
        for i in s:
            if i in dict:
                dict[i]+=1
            else:
                dict[i]=1
        for j in t:
            if j in dict:
                dict[j]-=1
        for i in s:
            if dict[i]!=0:
                return False
        
        return True
            


题目链接:349.两个数组的交集

思路:我的思路用的数组,遍历其中一个列表,判断元素是否在另一个列表中,若存在且结果数组中没有该元素,将该元素加入结果数组

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        rs=[]
        for i in nums1:
            if i in nums2 and i not in rs:
                rs.append(i)
        return rs


题目链接:202.快乐数

思路:定义一个集合来存放过程结果,如果求和出现在过程结果中,则说明陷入无限循环

class Solution(object):
    def get_sum(self,n):
        new_sum=0
        while n:
            n,r=divmod(n,10)
            new_sum+=r*r
        return new_sum
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        record =set()
        while True:
            n=self.get_sum(n)
            if n==1:
                return True
            elif n in record:
                return False
            else:
                record.add(n)
        


题目链接:两数之和

思路:定义一个哈希表,遍历数组,如果目标值减去当前数在哈希表中,则返回哈希表中的值的位置以及当前值的位置;若不存在,则将当前值以及位置存入哈希表中

class Solution:
    def twoSum(self,nums,target):
        dic={}
        for i,n in enumerate(nums):
            cp=target-n
            if cp in dic:
                return [dic[cp],i]
            else:
                dic[n]=i
        return []

            

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值