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

1 leetcode-Two Sum

2016-11-07 20:02 309 查看

版本1

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
英文:
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.
中文:
给一个整数数组,返回数组中相加等于target的两个数的索引.
假定每个输入都有符合要求的两个数
举例:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
'''
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) < 2:
return "array error"

Dict = {} #val->[index]
for index,val in enumerate(nums):
if Dict.has_key(val):
Dict[val].append(index)#重复元素
else:
Dict[val] = [index]

for val in nums:
if Dict.has_key(target - val):
if (target - val) == val:
if len(Dict[val]) < 2:#只有一个值为val的元素,重复使用,不能返回,第一次写的时候没考虑到,中枪了...
continue
else:
return Dict[val][0:2]
else:
return [Dict[val][0],Dict[target - val][0]]

if __name__ == "__main__":
s = Solution()
print s.twoSum([0,3,4,0],0)
raw_input()


时间复杂度,空间复杂度都为O(n).

版本2,短小精悍…

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) < 2:
return "array error"

for index,val in enumerate(nums):
if (target - val) in nums[index + 1:]:
return [index,index + 1 + nums[index + 1:].index(target - val)]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode TwoSum python