美文网首页
[LeetCode] 两数之和

[LeetCode] 两数之和

作者: 数据麻瓜 | 来源:发表于2018-11-03 03:25 被阅读0次

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

nums=[2, 7, 11, 15], target = 9,
因为nums[0] + nums[1] = 2 + 7 = 9, return([0, 1]).

M1: 创建哈希表,然后检索target-nums[i]是否在哈希表中。因为python的dict就是基于哈希表,所以建立哈希表等统建创建dict

class Solution:      
    def twoSum(self, nums, target):     
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}  #create a hash table
        for i in range(len(nums)): #遍历list
            comp = target-nums[i]  #计算target-number
            if comp in d:  #如果comp和nums[i]相加等于target且都在nums这个list中,则返回对应索引
                return(d[comp],i)
            d[nums[i]] = i  #创建索引

结果: Runtime: 36 ms, faster than 99.68% of Python3 online submissions for Two Sum

Notes: 是否需要检索的话都可以用哈希表提高效率?

相关文章

  • 【LeetCode通关全记录】1. 两数之和

    【LeetCode通关全记录】1. 两数之和 题目地址:1. 两数之和[https://leetcode-cn.c...

  • 双指针

    两数之和 click here for leetcode detail[https://leetcode-cn.c...

  • 纯C手撕leetcode-基本数据结构-hash table

    Hash table纯C实现两数之和和Hashtable 三数之和https://leetcode-cn.com/...

  • [LeetCode] TwoSum两数之和

    [LeetCode] TwoSum两数之和 Given an array of integers, returni...

  • LeetCode 专题 :双指针

    LeetCode 第 167 题:两数之和 II - 输入有序数组 传送门:167. 两数之和 II - 输入有序...

  • 常见算法面试题

    LeetCode题目精选 两数之和链接:https://leetcode-cn.com/problems/two-...

  • 两数之和-leetcode

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被...

  • LeetCode | 两数之和

    基础不好,笔试代码题没做好,校招没offer,赶紧来刷题 [TOC] 两数之和 这里采用两种方法来做,比较性能。 ...

  • [LeetCode] 两数之和

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 nums=[2, 7, 11, 15], targe...

  • leetcode 两数之和

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的...

网友评论

      本文标题:[LeetCode] 两数之和

      本文链接:https://www.haomeiwen.com/subject/jswhxqtx.html