两数之和

题源:leetcode

链接:https://leetcode-cn.com/problems/two-sum/

 暴力枚举的代码不描述了,即两次for循环。

哈希表:

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         unordered_map<int, int> hashtable;
 5         for (int i = 0; i < nums.size(); ++i) {
 6             auto it = hashtable.find(target - nums[i]);
 7             if (it != hashtable.end()) {
 8                 return {it->second, i};
 9             }
10             hashtable[nums[i]] = i;
11         }
12         return {};
13     }
14 };
原文地址:https://www.cnblogs.com/hosheazhang/p/15058130.html