0
点赞
收藏
分享

微信扫一扫

leetcode分类刷题 -- 哈希应用

小迁不秃头 2022-02-12 阅读 55

leetcode 第一题 两数之和 -- 简单

力扣icon-default.png?t=M0H8https://leetcode-cn.com/problems/two-sum/

题目中没有说明数组是有序的,要返回原始数组的中index,因此不能排序,如果用暴力的话,应该是两层for循环,用哈希的话,则可以省掉第二层for循环,其次针对这种加法的,可以转成减法,避免溢出

class Solution:
    def twoSum(self,nums,target):
        record = dict()
        for idx,val in enumerate(nums):
            if target - val not in record:
                record[val] = idx
            else:
                return [record[target-val],idx]  


if __name__ == "__main__":
    nums = [2,7,11,15]
    target = 9
    print(Solution().twoSum(nums,target))

举报

相关推荐

0 条评论