题意:给定一个目标值target,找到两个数的和为target,返回这两个数的下标
用map记录每个数的下标,并用于查找
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> ans; map<int,int> m; for(int i = 0; i < nums.size(); ++i){ m[nums[i]] = i; } for(int i = 0; i < nums.size(); ++i){ if(m.find(target - nums[i]) != m.end() && m[target - nums[i]]!= i){ ans.push_back(i); ans.push_back(m[target - nums[i]]); break; } } return ans; } };
时间: 2024-10-11 05:49:10