美文网首页
Two sum (二值和)

Two sum (二值和)

作者: 穿越那片海 | 来源:发表于2017-03-05 15:09 被阅读0次

    Easy, Array/String

    给定一个整数数列和一个目标和,寻找数列中的两个数加起来等于目标值,返回两数的索引。假设只有一个解,同一个数不能被使用两次。

    Example:
    Given nums = [2, 7, 11, 15], target = 9,

    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

    利用字典存储实现复杂度为O(n)的算法

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            if len(nums) < 2:
                return False
            pair_dict = {}
            for i, num in enumerate(nums):
                if num in pair_dict:
                    return [pair_dict[num], i]  
                else:
                    #存储遍历过程当前值得对应值
                    pair_dict[target - num] = i 
    

    相关文章

      网友评论

          本文标题:Two sum (二值和)

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