首页 > 其他 > 详细

LintCode: Two Sum

时间:2015-12-01 12:43:51      阅读:274      评论:0      收藏:0      [点我收藏+]

C++

hash map

把查找2个数的过程转换为查找1个数

借用STL容器 unordered_map

 1 class Solution {
 2 public:
 3     /*
 4      * @param numbers : An array of Integer
 5      * @param target : target = numbers[index1] + numbers[index2]
 6      * @return : [index1+1, index2+1] (index1 < index2)
 7      */
 8     vector<int> twoSum(vector<int> &nums, int target) {
 9         // write your code here
10         vector<int> result;
11         int n = nums.size();
12         if (0 == n) {
13             return result;
14         }
15         // first value, second index
16         unordered_map<int, int> hash(n);
17         for (int i = 0; i < n; i++) {
18             if (hash.find(target - nums[i]) != hash.end()) {
19                 result.push_back(hash[target - nums[i]]);
20                 result.push_back(i + 1);
21                 return result;
22             } else {
23                 hash[nums[i]] = i + 1;
24             }
25         }
26     }
27 };

 

LintCode: Two Sum

原文:http://www.cnblogs.com/CheeseZH/p/5009591.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!