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

Two Sum

时间:2015-07-29 11:40:57      阅读:126      评论: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 not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

直接暴力法O(n*n)超时,因此需采用hashmap,这里采用map来存储数据并进行搜索,其实现为

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4        vector<int> res;
 5        map<int,int> tmp;
 6        for(int i=0;i<nums.size();i++)
 7        {
 8            if(!tmp.count(nums[i]))
 9                tmp.insert(pair<int,int>(nums[i],i+1));
10            if(tmp.count(target-nums[i]))
11            {
12                int n=tmp[target-nums[i]];
13                if(n<i+1)
14                {
15                    res.push_back(n);
16                    res.push_back(i+1);
17                    return res;
18                }
19            }
20        }
21        return res;
22     }
23 };

 

红黑树。

Two Sum

标签:

原文地址:http://www.cnblogs.com/zl1991/p/4685248.html

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