给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
// 56ms
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
const int numsSize = nums.size();
if(numsSize){
for(int i=0; i<numsSize-1; i++) {
int val = target - nums[i];
for(int j=i+1; j<numsSize; j++) {
if(val == nums[j]) {
vector<int> result(2);
result[0] = i;
result[1] = j;
return result;
}
}
}
}
return vector<int>(2);
}
};
// 8ms use map to increase find speed
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
const int numsSize = nums.size();
if(numsSize){
map<int, int> valueMap;
for(int j=1; j<numsSize; j++) {
valueMap[nums[j]] = j;
}
for(int i=0; i<numsSize-1; i++) {
int val = target - nums[i];
map<int, int>::iterator itor = valueMap.find(val);
if((itor != valueMap.end())&&(itor->second != i)) {
vector<int> result(2);
result[0] = i;
result[1] = itor->second;
return result;
}
}
}
return vector<int>(2);
}
};