**leetcode 第一题
题目如下:
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].
初一看到题目,很简单,双层循环就可以找到那一组数列。
所以很easy啰~
python代码如下
class Solution:
def twoSum(self, nums, target):
t=0
for i in range(0,len(nums)):
for j in range(i,len(nums)):
if nums[i]+nums[j]==target and i!=j:
return (i,j)
代码通过,结果如下:
嗯,不太满意(废话,这O(
N2
)的开销,能好才怪)……
改呗,python提供了字典数据结构,这就是hash的高级应用,改用字典降低时间开销,恩说干就干!
class Solution:
def twoSum(self, nums, target):
dict={}
for i in xrange(len(nums)):
x=nums[i]
dict[x]=i
if target-x in dict:
return (dict[x],dict[target-x])
看起来很不错了,大大提升时间效率,BTW,结果出问题了:
example:
nums=[5, 22, 3, 2, 7, 16],target=10
结果:(0, 0)
结果不是我们期待的(2, 4)
改改改……
换一下逻辑,又是一个低级错误~~~
class Solution:
def twoSum(self, nums, target):
dict={}
for i in xrange(len(nums)):
x=nums[i]
if target-x in dict:
return (i,dict[target-x])
dict[x]=i
好了,上OJ
还是刚刚达到及格线……不想改了
第一题完成!