传送门:两数之和
解析:
1. 暴力遍历每一个数,使用unordered_map维护1 ~ (i - 1),区间中哪些数出现了
代码:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> hash; for (int i = 0, n = nums.size(); i < n; ++i) { auto it = hash.find(target - nums[i]); if (it != hash.end()) { return {i, it->second}; } hash[nums[i]] = i; } return {}; } };