leetcode Two Sum
来源:互联网 发布:国考公务员 知乎 编辑:程序博客网 时间:2024/05/29 17:50
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
my code:
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ mydict = {} index1 = -1 index2 = -2 if len(nums) < 2: return [-2, -1] for i in xrange(len(nums)): if nums[i] not in mydict.keys(): mydict[nums[i]] = i#这里要注意,如果有重复值的话,这里也就记录最近的一个index dif = target - nums[i] if mydict.has_key(dif) : ind = mydict[dif] if i > ind: index2 = i + 1 index1 = ind + 1 return index1,index2
other’s code:
http://jelices.blogspot.hk/2014/06/leetcode-two-sum.html
class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): processed = {} for i in range(0, len(num)): if target-num[i] in processed: return [processed[target-num[i]]+1,i+1] processed[num[i]]=i
Note:
we can directly check whether a dict has a key by
if a in mydict:
关于数组的题目 要记得用 hash, sort, binary search(two pointers, or traditional one)
这里还可以使用binary search 的思想,sort之后,使用head pointer i以及tail pointer j,来搜索 two sum 的解空间。two sum!!!!!
http://www.cnblogs.com/springfor/p/3859618.html#3298209
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- 趣学Python-教孩子学编程--第十章
- Unity3d学习05
- 硬盘分类及数据恢复
- Spring学习笔记(十一):关于微信开发时,用户名包含表情,保存到数据库出错的解决办法
- mysql和oracle中的日期型和字符串的转换以及各个字母代表
- leetcode Two Sum
- Xml文档的读写
- 对懒汉式和饿汉式的理解
- codevs2602 最短路径问题
- 不错的网站
- Unity3d学习06
- spine 破解 闪退打不开
- js适用于多个input标签的文字提示
- 项目简记——关于spring与structs2结合的理解