lc1 两数之和
给定一个整数数组 nums 和整数目标值 target,请在这个数组中找到 和为目标值 target 的那 两个 回到他们的数组下标。 你可以假设每个输入只对应一个答案。然而,答案中不能重复数组中的相同元素。 您可以按任何顺序返回答案。
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/two-sum
class Solution {
public: vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hashmap; ///次历数组 for(int i=0;i<nums.size();i ){
//通过find 拿到迭代器 auto it = hashmap.find(target-nums[i]); //如果迭代器 没到达结尾 表示找到了 if(it != hashmap.end()){
//it->表示值 我们在这里保存的是 索引 return {
it->second,i}; } ///找不到就更新哈希表 hashmap[nums[i]] = i; } return {
}; } };