您的位置:首页 > 其它

Two Sum

2015-05-29 21:29 176 查看
题目:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

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

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

代码1:

class Solution:

# @param {integer[]} nums

# @param {integer} target

# @return {integer[]}

def twoSum(self, nums, target):

intger = []

for num in nums:

if num < target:

if ((target-num) in nums) and (nums.index(target-num)!=nums.index(num)):

index1, index2 = min(nums.index(target-num),nums.index(num)), max(nums.index(target-num),nums.index(num))

intger = [index1, index2]

return intger

会出现time limited exceed

代码2:

class Solution:

# @param {integer[]} nums

# @param {integer} target

# @return {integer[]}

def twoSum(self,num,target):

process = {}

for index in range(len(num)):

if target-num[index] in process:

return [process[target-num[index]]+1,index+1]

process[num[index]] = index

代码3:

class Solution:

# @param {integer[]} nums

# @param {integer} target

# @return {integer[]}

def twoSum(self, nums, target):

n = len(nums)

tmp = sorted(nums)

i = 0

j = n-1

while(i<j):

if tmp[i]+tmp[j]==target:

index1 = nums.index(tmp[i])+1

if nums.index(tmp[j])+1==index1:

index2 = nums.index(tmp[j],index1)+1

else:

index2 = nums.index(tmp[j])+1

index1, index2 = min(index1,index2) ,max(index1,index2)

return [index1, index2]

elif tmp[i]+tmp[j]<target:

i += 1

else:

j -= 1

总结:

代码1使用list进行遍历,其大致时间复杂度为O(n*n)

代码2使用dict,进行搜索时只需要常数时间。时间复杂度为O(n*1)=O(n)

代码3先将nums排序,然后从两端才开始搜索。时间复杂度为O(n),空间复杂度为O(1)。此法优于代码2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: