您的位置:首页 > 编程语言 > C语言/C++

leetcode:Two Sum

2016-08-03 21:31 253 查看
1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

C++ Version:

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> lmap;
vector<int> result;
for(int i = 0; i < nums.size(); ++i)
{
int temp = target - nums[i];
if(lmap.find(temp) != lmap.end())
{
result.push_back(lmap[temp]);
result.push_back(i);
return result;
}
lmap[nums[i]] = i;
}
return result;
}
};


Python Version:

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Two Sum C++ python