【LeetCode】面试算法总结@哈希表

1、LeetCode----242. 有效的字母异位词

https://leetcode-cn.com/problems/valid-anagram/submissions/
在这里插入图片描述

Solution1

#首先考虑将两个字符串转换为列表,遍历其中一个列表
#如果数据在另外一个列表中,删除另外一个列表中的数据直至结束
#当能够完成所有的遍历,说明返回true
#当然应该首先考虑的是两字符串是否长度相等,如果不相等则肯定返回false
class Solution1:
    def isAnagram(self, s: str, t: str) -> bool:
        s = list(s)
        t = list(t)
        if len(s)!=len(t):
            return 0
        for i in s:
            if i in t:
                t.remove(i)
            else:
                return 0
        return 1

Solution2

#我们可以通过直接将两个字符串转换成列表进行排序
#最后检查两个列表是否相等
#这样做减少了一个数量级的时间复杂度
class Solution2:
    def isAnagram(self, s: str, t: str) -> bool:
        s = list(s)
        s.sort()
        t = list(t)
        t.sort()
        if not s and not t:
            return 1
        if not s or not t:
            return 0
        if s == t:
            return 1
        else:
            return 0

Solution3

#若果知道python的一个sorted函数的话,代码可以说非常简洁
#直接排序两个字符串检查是否相等,返回检查的结果
class Solution3:
    def isAnagram(self, s: str, t: str) -> bool:
        return sorted(s) == sorted(t)

2、LeetCode----15. 三数之和

https://leetcode-cn.com/problems/3sum/
在这里插入图片描述

基本思路

#首先能够想到的是使用三层遍历
#但是我们可以优化到两层,应为到第二层的时候我们就应该知道对应的第三个数是什么
#求前两个数的和的相反数就是第三数,只要检查这个数是否在列表中即可
#但是可惜是最后的两个case还是跑不过,时间超时了。
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        if not nums:
            return
        n = len(nums)
        if n < 3:
            return
        answer = []
        for i in range(n):
            check = nums.copy()
            check.remove(nums[i])
            for j in range(i + 1, n):
                check.remove(nums[j])
                tem = -(nums[i] + nums[j])
                if tem in check:
                    temp = sorted([nums[i], nums[j], tem])
                    if  temp not in answer:
                        answer.append(temp)
        return answer
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值