leetcode 1 Two Sum
来源:互联网 发布:php 文件上传类 编辑:程序博客网 时间:2024/03/28 18:27
Two Sum
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
class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): nums=zip(num[:],range(len(num))) s=sorted(nums,key=lambda nums:nums[0]) #print s i=0 j=len(s)-1 while i<j: tmp=s[i][0]+s[j][0] if tmp==target: i,j=s[i][1]+1,s[j][1]+1 if i>j: i,j=j,i return (i,j) elif tmp>target: j-=1 else: i+=1
更快更好的方法:用字典记录之前的所有数字,当在位置i时,O(1)的时间即可知道target-num[i]是否存在。 O(n)
class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): d={} for i in xrange(len(num)): if target-num[i] in d: return(d[target-num[i]]+1,i+1) d[num[i]]=i
0 0
- LeetCode 1 - Two Sum
- leetcode 1 Two Sum
- Leetcode【1】:Two Sum
- [leetcode 1] Two Sum
- 【leetcode-1】Two Sum
- [leetcode 1] Two Sum
- [Leetcode] 1 - Two Sum
- LeetCode (1) Two Sum
- LeetCode 1:《Two Sum》
- LeetCode | #1 Two Sum
- leetcode-1 Two Sum
- Two Sum | LeetCode(1)
- [Leetcode]1Two Sum
- leetcode 1 Two Sum
- leetcode #1 Two Sum
- leetcode 1:Two Sum
- LeetCode 1 Two Sum
- leetcode #1 two sum
- Insert Interval
- Ubuntu 下安装postfix 配置
- 计算机视觉方向的一些顶级会议和期刊
- easyui 一些使用技巧
- Struts2基础之文件上传
- leetcode 1 Two Sum
- IOS视图生命周期
- Autolayout 下的 Animation
- mysql更改数据文件目录及my.ini位置。
- 第五讲计算结果的可视化
- 七牛用户搭建c# sdk的图文解说
- jqGrid在页面进行编译
- 缓慢变化思想10
- 公共POI导出Excel方法--java