Two Sum
2014-09-19 06:57
183 查看
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):
map = {}
for i in range(len(num)) :
if target - num[i] in map:
return (map[target - num[i] ] + 1, i+1)
else :
map[num[i] ] = i
return None
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):
map = {}
for i in range(len(num)) :
if target - num[i] in map:
return (map[target - num[i] ] + 1, i+1)
else :
map[num[i] ] = i
return None
相关文章推荐
- 1. Two Sum
- LeetCode Two Sum
- 【Leetcode】1. Two Sum
- 1. Two Sum
- [LeetCode]1. Two Sum
- LeetCode:Two Sum
- LeetCode之Two Sum
- Two Sum
- two sum
- LeetCode:1. Two Sum
- Two Sum
- [leetcode]Two Sum
- Two Sum
- LeetCode No.1 Two Sum
- leetcode.-1.Two Sum
- LeetCode 167 Two Sum 2-Input array is sorted
- LeetCode笔记1--Two Sum
- 1 Two sum
- two sum
- 【LeetCode】1. Two Sum