您的位置:首页 > 其它

LeetCode —-Two Sum

2017-12-24 17:31 387 查看

题目

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

解决

首先想到的是采用双层循环,解决这个问题。代码如下:

class Solution:
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(len(nums)):
if nums[i]+nums[j]==target and i !=j:
return [i,j]


运行结果虽然没有错误,但是提交代码时出现TLM,超时了。看来服务器限制算法空间复杂度了,不支持O(n^2)

所以下边考虑修改空间复杂度,反复考虑后采用反证法解决复杂度问题。哈哈哈哈(反证法)。复杂度降低为O(n),完美提交

class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
num = target - nums[i]
if num in nums:
j = nums.index(num)
if i != j:
return [i,j]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: