LeetCode-1- Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

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

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

简言之,查找给定数组内两个数,使得两数和为给定的target

思路:

遍历给定数组,用一个哈希表存放已经遍历过的值,key是nums中的值,value是其位置索引。

对于当前遍历的nums[i],查找哈希表中是否存在target-nums[i],若存在,则返回二者索引,否则将(key=nums[i],value=i)放入哈希表中,继续遍历

时间复杂度:O(n)

python代码如下,已AC:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dictMap = {}
        for index, value in enumerate(nums):
            if target - value in dictMap:
                return [dictMap[target - value] , index ]
            dictMap[value] = index

博客园博客:欠扁的小篮子

坚持原创技术分享,您的支持将鼓励我继续创作!
0%