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

Two Sum

时间:2016-08-22 23:05:57      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are NOTzero-based.

 Notice

You may assume that each input would have exactly one solution

Example

numbers=[2, 7, 11, 15], target=9

return [1, 2]

 

Analyse: Be aware of that one element could appear more than once. Map each element into an array.

Runtime: 10ms

 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         
11         // use a hash map to store array information
12         // the key is element in nums, value is the index of that element
13         unordered_map<int, vector<int> > um; 
14         for (int i = 0; i < nums.size(); i++) {
15             um[nums[i]].push_back(i);
16         }
17         
18         // scan the array and find if (target - element) in the hash map
19         vector<int> result;
20         for (int i = 0; i < nums.size(); i++) {
21             if (um.find(target - nums[i]) != um.end()) {
22                 // a value appears more than once and happens to equal to half of target
23                 if (nums[i] == target - nums[i]) {
24                     result.push_back(um[nums[i]][0] + 1);
25                     result.push_back(um[nums[i]][1] + 1);
26                 }
27                 else {
28                     int index1 = um[nums[i]][0], index2 = um[target - nums[i]][0];
29                     result.push_back(min(index1, index2) + 1);
30                     result.push_back(max(index1, index2) + 1);
31                 }
32                 break;
33             }
34         }
35         return result;
36     }
37 };

 

Two Sum

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/5797193.html

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