[LeetCode]#1 Two Sum

LeetCode第一题,用Python做。56ms

 

一、题目

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.遍历numbers,设当前值为x;

2.利用目标值target,与numbers[]中一个数x做减法后得y;

3.numbers[]中是否存在y?  

  若y存在,则说明x + y = target,按从小到大顺序输出x, y的下标即可;

  若y不存在,则说明当前x不能与其他值加和为target,遍历下一个x。

 

四、难点

1.按照上述思路,其实是一个O(n^2)的复杂度。第一层是遍历numbers[]得x,第二层是对于一个x去一个一个试y。这样实现很简单,但当numbers[]很大时可能会超时。试了一下果然超时了。

2.一般O(n^2)可以转化为O(nlogn),即第一层遍历numbers[]得x,第二层用二分查找的方法去试y。这样做的前提是numbers[]是有序的,比较麻烦。

3.看了一下本题的tag是hash,可以用空间换时间。这样的话代价损耗在以下两个步骤:

  1)建立hash表

  2)遍历numbers[]得x

  这二者复杂度都是0(n),所以整体的复杂度是O(n)。

  具体做法:

  1)Python中dict类型是hash的,对于Key-value,好像没有对value的检索;所以就把numbers[]中的x当key,下标当value。当然这样做是有前提的,即本题中没有重复的x存在,所以不存在相同key对应不同value的情况。

  2)遍历numbers[]得x,target-x=y,在dict中检索key为y的项。若存在,则key即为下标

  3)判断x,y下标大小,按从小到达顺序返回即可。

 

五、Python代码

 1 class Solution:
 2     # @param {integer[]} nums
 3     # @param {integer} target
 4     # @return {integer[]}
 5     def twoSum(self, nums, target):
 6         _dict = {}
 7         for i in range(len(nums)):
 8             _dict[nums[i]] = i     
 9         
10         _target = target
11         first = 0
12         second = 0
13         for i in range(len(nums)):
14             _target = target - nums[i]
15             key = _dict.get(_target, "no")
16             if (key != "no") and (key != i):
17                 first = i + 1
18                 second = key + 1
19             else:
20                 pass
21         
22         if first < second:
23             return [first, second]
24         else:
25             return [second, first]

 

六、总结

1.很开心自己有了复杂度的意识,也有了一些基本的常识。补了一段时间的数据结构还是有用的。

2.想不出解决方案时,可以看一下讨论,或者题目本身的tag,也许就能柳暗花明。

posted @ 2015-06-29 17:16  面包包包包包包  阅读(135)  评论(0编辑  收藏  举报