题目:
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.
代码:
LeetCode第一题,今天回国偷来做一下,还是蛮有意思的。
乍一看这个题,当然遍历两遍,稳稳找出结果:
"""遍历两边找出来,时间复杂度O(N^2)"""
def twoSum(self, nums, target):
for i in nums:
for j in range(nums.index(i)+1,len(nums)):
if(i + nums[j] == target):
return [nums.index(i),j]
结果运行的好慢哦:
还好用的是python,网上查了下,java这样写全都报超时错误,时间复杂度太高。
于是,遍历一遍,在剩余列表中找到第二个元素即可:
"""遍历一遍找出来,时间复杂度O(N)"""
def twoSum2(self, nums, target):
for i in nums:
try:
#找出第二个元素是否存在,存在返回位置,从当前元素下一位开始找,避免重复
j = nums[nums.index(i)+1:].index(target - i)+nums.index(i)+1
return [nums.index(i),j]
except:
continue
明显快多啦:)
网上有查了下,居然没有想到python的字典,发现用列表写好蠢啊,哎~~~还是要多练习!
边找边存入字典:
"""用字典实现,时间复杂度O(N)"""
def twoSum3(self, nums, target):
dict = {}
for i in range(len(nums)):
x = nums[i]
#判断第二个元素的值是否存在在字典中
if target-x in dict:
return (dict[target-x], i)
#将元素按照{key:index}方式存入字典
dict[x] = i
速度也明显提升: