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, 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].
题解:
找到两个数使其和为target,返回两个数的下标。
unordered_map<int, int>:
key:待查找数组中元素值
value:元素在数组中下标值
Solution1
/* O(n) by c++ */
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//Key is the number and value is its index in the vector.
unordered_map<int, int> map;
vector<int> result;
int size = nums.size();
for (int i = 0; i < size; i++) {
int numtofind = target - nums[i];
if (map.find(numtofind) != map.end()) {
result.push_back(map[numtofind]);
result.push_back(i);
}
map[nums[i]] = i;
}
return result;
}
};