LeetCode 1. Two Sum (Easy)

来源:互联网 发布:单片机数码管接线 编辑:程序博客网 时间:2024/06/05 22:41

题目描述:

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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

题目大意:给出一个数组,找出值相加等于target的两个数字并输出其下标。

思路:暴力法:对于每个数组元素,判断剩余元素与其相加是否为target,复杂度O(n^2)
哈希法:设当前元素为x。遍历数组,如果target - x存在于哈希表,则输出其下标,复杂度O(n),即遍历数组的复杂度。因为我对c++的map不熟,就用python的dict来做了。
python代码(哈希):

class Solution(object):    def twoSum(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """        dict = {}        for i in range(len(nums)):            if dict.get(target - nums[i], None) == None:                dict[nums[i]] = i            else:                return (dict[target - nums[i]], i) 
原创粉丝点击