LeetCode Two Sum
2018-02-22 12:22
471 查看
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, and you may not use the same element twice.Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].需要了解一下unordered_map;class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int>hash;
vector<int> result;
for(int i=0;i<nums.size();i++){
int numberToFind=target-nums[i];
if(hash.find(numberToFind)!=hash.end()){
result.push_back(hash[numberToFind]);
result.push_back(i);
return result;
}
hash[nums[i]]=i;
}
return result;
}
};
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].需要了解一下unordered_map;class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int>hash;
vector<int> result;
for(int i=0;i<nums.size();i++){
int numberToFind=target-nums[i];
if(hash.find(numberToFind)!=hash.end()){
result.push_back(hash[numberToFind]);
result.push_back(i);
return result;
}
hash[nums[i]]=i;
}
return result;
}
};
相关文章推荐
- 【LeetCode】1:Two Sum
- LeetCode_Two Sum
- Leetcode-Two Sum
- [LeetCode]Two Sum
- [LeetCode] 120: Two Sum
- 【Leetcode】【Medium】Two Sum
- leetcode001:Two Sum
- LeetCode 1. Two Sum
- leetcode 1.Two Sum (水题,STL_map)
- LeetCode Two sum
- leetcode [001] : Two Sum
- 算法分析与设计——LeetCode Problem.1 Two Sum
- Leetcode 1. Two Sum
- Two Sum-----LeetCode
- LeetCode - Two Sum 完整代码(python)
- [LeetCode]-001-Two Sum
- LeetCode(1)Two Sum
- [LeetCode]Two Sum
- 【leetcode】Two Sum
- LeetCode(62)-Two Sum