您的位置:首页 > 编程语言 > Python开发

leetcode01 Two Sum 寻找列表中和为定值的元素位置

2017-08-30 18:25 423 查看
刷刷leetcode。

problem description:

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].

我的解法(很蠢):

# my solution
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)):
while nums[i] + nums[j] == target:
return i,j

sol = Solution()
sol.twoSum([3,2,4],6)
别人的优质解法,复杂度为O(n)

class Solution(object):
def twoSum(self, nums, target):
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i
print buff_dict

sol = Solution()
sol.twoSum([3,2,6,5],7)

解读一下别人的优质解法:

新建空字典buff_dict,将前面出现过的目标值-数字作为key,数字的位置作为value存入buff_dict,打个比方列表是[2,4,5,3],定值是7。我们从位置0开始,先存入{7-2:0},再存入{7-4:1},所以buff_dict现在是{5:0,3:1},只要后面出现5或者3,就说明我们找到了元素和为8的两个元素。

总结:生成一个以目标值减去前面出现的元素为key,出现的元素位置为value的字典。这样我们就知道,前面的元素需要这些值就可以满足和为定值的条件了,后面只要出现一个,就直接把value和当前值的位置作为结果返回。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法 python
相关文章推荐