题解 | #两数之和#
两数之和
https://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
#include <unordered_map> #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param numbers int整型vector * @param target int整型 * @return int整型vector */ vector<int> twoSum(vector<int>& numbers, int target) { // write code here vector<int> re; if (numbers.size()==0) { return re; } unordered_map<int, int> map; //哈希容器,将两值关联 for(int i=0; i<numbers.size();i++) { map[numbers[i]]=i; } int sub=0; for (int i=0; i<numbers.size(); i++) { sub=target-numbers[i]; if (map.count(sub)==1&&map[sub]!=i){ //差值存在且不为本身 int left=(map[sub]>i)?i:map[sub]; //比较大小,依次放入 int right=(map[sub]>i)?map[sub]:i; re.push_back(left+1); re.push_back(right+1); break; //找到一组就结束 } } return re; } };