输入:[3, 2, 4], 6
返回值:[2, 3]
class Solution {
public:
/**
*
* @param numbers int整型vector
* @param target int整型
* @return int整型vector
*/
vector<int> twoSum(vector<int>& numbers, int target) {
map<int, int> m; //定义hash表,第一个值是key,第二个是value
vector<int> res;
for (int i = 0; i < numbers.size(); i++) {
m[numbers[i]] = i; //对 hash 的 key 赋值
}
for (int i = 0; i < numbers.size(); i++) {
int diff = target - numbers[i];
if (m.find(diff) != m.end() && m[diff] > i) { //查找到的不等于hash的最后一个 ,并且 “m[diff] > i”
res.push_back(i + 1); //“i+1” 和 “m[diff]+1” 压进去
res.push_back(m[diff] + 1);
break;
}
}
return res;
}
};
两数之和
最新推荐文章于 2023-05-27 14:53:45 发布