码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode 1] Two Sum

时间:2015-03-01 19:41:24      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

算法渣,现实基本都参考或者完全拷贝[戴方勤(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. 存储位置信息尤为重要

 

[LeetCode 1] Two Sum

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!