【1】Two Sum (2018年11月9日,k-sum专题,算法群衍生题)

给了一个数组 nums, 和一个 target 数字,要求返回一个下标的 pair, 使得这两个元素相加等于 target 。

题解:我这次最大范围的优化代码, hash-table + one pass,时间复杂度 O(N),空间复杂度 O(N)。重点在于动态找,一边生成hash-table的同时去找答案,不是先生成hash-table再开始找答案。

 1 //这种类似 hash 的能用 unordered_map 就不要用 map, hash-table + one pass
 2 class Solution {
 3 public:
 4     vector<int> twoSum(vector<int>& nums, int target) {
 5         const int n = nums.size();
 6         unordered_map<int, int> mp;
 7         vector<int> ans(2);
 8         for (int i = 0; i < n; ++i) {
 9             int key = target - nums[i];
10             if (mp.find(key) != mp.end()) {
11                 ans[0] = mp[key];
12                 ans[1] = i;
13                 break;
14             }
15             mp[nums[i]] = i;
16         }
17         return ans;
18     }
19 };
View Code

相关文章:

  • 2022-12-23
  • 2021-12-08
  • 2021-07-20
  • 2022-12-23
  • 2021-12-29
  • 2021-10-24
  • 2022-01-11
  • 2021-05-29
猜你喜欢
  • 2021-04-04
  • 2021-11-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-15
  • 2021-11-14
相关资源
相似解决方案