[LeetCode] Two Sum

算法渣,现实基本都参考或者完全拷贝[戴方勤(soulmachine@gmail.com)]大神的leetcode题解,此处仅作刷题记录。

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target) {
 4         unordered_map<int, int> mapping;
 5         vector<int> result;
 6         for (int i = 0; i < numbers.size(); i++) {
 7             mapping[numbers[i]] = i; // 此处存储了位置信息
 8         }
 9 
10         for (int i = 0; i < numbers.size(); i++) {
11             const int gap = target - numbers[i];
12             // 循环,若找到了键且对应的值满足条件,则退出
13             if (mapping.find(gap) != mapping.end() && mapping[gap] > i) {
14                 result.push_back(i + 1);
15                 result.push_back(mapping[gap] + 1);
16                 break;
17             }
18         }
19         return result;
20     }
21 };

杂记:

1. Unordered Map

Internally, the elements in the unordered_map are not sorted in any particular order with respect to either their key ormapped values, but organized into buckets depending on their hash values to allow for fast access to individual elements directly by their key values (with a constant average time complexity on average).

unordered_map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.

2. 成员函数 find

Searches the container for an element with k as key and returns an iterator to it if found, otherwise it returns an iterator to unordered_map::end (the element past the end of the container).

注:与[]运算符不同

3. 存储位置信息尤为重要

4. 题目明确表示有一个答案,所以不会存在元素重复的情况

原文地址:https://www.cnblogs.com/Azurewing/p/4307440.html