1. Two Sum
2016-04-05 08:33
441 查看
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].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
Subscribe to see which companies asked this question
给定一个整数数组和一个目标值,返回两个数的索引,这两个数之和等于目标值
结果见下图(5516 ms):
将输入的整数数组转换为dict,key为数组中的值,value为该值对应的索引
对于每一个key,判断target-key是否在dict中,再则返回[key对应的value, target-key对应的value],如果不在则继续下一个
时间复杂度变成O(n),我的python实现如下:
耗时只有上次的1/100,如下图(60 ms):
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].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
Subscribe to see which companies asked this question
给定一个整数数组和一个目标值,返回两个数的索引,这两个数之和等于目标值
第一次尝试,最低效的方法
采用遍历的方法,时间复杂度为O(n^2),代码如下:class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): for j in range(i+1,len(nums)): if nums[i] + nums[j] == target: return [i,j]
结果见下图(5516 ms):
别人家孩子的做法
在此之前,我想到过使用比较好的数据结构肯定可以简化实现过程,dict或者其他,但最终没有想到解决方案,于是在讨论区逛了逛,他们好过分,真的可以用dict来很简单的解决,思路是这样的:将输入的整数数组转换为dict,key为数组中的值,value为该值对应的索引
对于每一个key,判断target-key是否在dict中,再则返回[key对应的value, target-key对应的value],如果不在则继续下一个
时间复杂度变成O(n),我的python实现如下:
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ positions = dict(zip(nums, range(len(nums)))) for i in range(len(nums)): position = positions.get(target-nums[i], None) if position: return [i, position]
耗时只有上次的1/100,如下图(60 ms):