leetcode 1 Two Sum
2015-03-18 15:24
375 查看
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
思路:先排序;再从两头向中间找 O(nlogn)
更快更好的方法:用字典记录之前的所有数字,当在位置i时,O(1)的时间即可知道target-num[i]是否存在。 O(n)
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
思路:先排序;再从两头向中间找 O(nlogn)
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
相关文章推荐
- Two Sum--LeetCode
- [leetcode]: 1. Two Sum
- 【LeetCode】第1题: Two Sum
- Leetcode 1. Two Sum
- Leetcode -- Two Sum
- leetcode之Two Sum
- LeetCode - Two Sum 完整代码(GO)
- 【leetcode】【1】Two Sum
- leetcode No.1 Two Sum
- leetcode------第一题 Two Sum
- LeetCode-Two Sum
- leetcode-Two Sum
- LeetCode 1.Two Sum
- leetcode 刷题题解(c++) 1.Two Sum (hash表,排序+二分查找)
- [leetcode 1] Two Sum
- LeetCode 01 Two Sum
- leetcode之Two Sum
- leetcode 1 -- Two Sum
- LeetCode|Two Sum
- [Leetcode]之一《two sum》解题报告