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:
C++ Version:
Python Version:
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
- LeetCode 第一题,Two Sum
- leetCode 刷题记录-1. Two Sum
- 【Leetcode】Two Sum
- LeetCode1 Two Sum
- [LeetCode] Two Sum
- [LeetCode]1 Two Sum
- leetcode 1 Two Sum 两数之和
- [leetcode, python] Two Sum 两数之和等于某数
- LeetCode Two Sum
- LeetCode:Two Sum
- LeetCode: Two Sum
- leetcode--Two Sum
- LeetCode-Easy刷题(1) Two Sum
- LeetCode之Two Sum
- LeetCode 01 Two Sum
- LeetCode:Two Sum
- LeetCode----Two Sum
- LeetCode: Two Sum
- LeetCode | Two Sum