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

LintCode 56. 两数之和

时间:2018-01-27 11:35:56      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:com   ack   bsp   pre   ref   cep   write   blog   style   

题目:

给一个整数数组,找到两个数使得他们的和等于一个给定的数 target

你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 0 到 n-1

样例

给出 numbers = [2, 7, 11, 15], target = 9, 返回 [0, 1].

挑战 

Either of the following solutions are acceptable:

  • O(n) Space, O(nlogn) Time
  • O(n) Space, O(n) Time

 

解:要找A+B=target,可以在知道A的情况下,直接找target-A是否存在。

class Solution {
public:
    /*
     * @param numbers: An array of Integer
     * @param target: target = numbers[index1] + numbers[index2]
     * @return: [index1 + 1, index2 + 1] (index1 < index2)
     */
    vector<int> twoSum(vector<int> &numbers, int target) {
        // write your code here
        vector<int> res;
        map<int,int> m;
        int sz=numbers.size();
        for(int i=0;i<sz;i++)
        {
            if(m.find(target-numbers[i])!=m.end())
            {
                res.push_back(m[target-numbers[i]]);
                res.push_back(i);
                return res;
            }
            m[numbers[i]]=i;
        }
        return res;
    }
};

 

LintCode 56. 两数之和

标签:com   ack   bsp   pre   ref   cep   write   blog   style   

原文地址:https://www.cnblogs.com/zslhg903/p/8362052.html

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