本文共 833 字,大约阅读时间需要 2 分钟。
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].
思路:用一个hash表存储每个元素及其相应的index,并在数组中进行循环查找
vector twoSum(vector & nums, int target) { if (nums.size() <= 1)return vector {}; unordered_mapres; vector idx; for (int i = 0; i < nums.size(); i++)res[nums[i]] = i; for (int i = 0; i < nums.size(); i++){ int tmp = target - nums[i]; if (res.find(tmp) != res.end() && res[tmp] > i){ idx.push_back(i), idx.push_back(res[tmp]); return idx; } } return idx;}
转载地址:http://yaxei.baihongyu.com/