two sum - leetcode

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

1/ 首先想到的是 通过两次循环去寻找 这两个数,找到后立刻返回。

但是当提交运行的时候,会报错,运行时间过长。    

2/ 想到的另一种方法是,先通过排序(nlgn),然后通过两个指针去前后遍历数组(n)

3/ 最后一种方法在网上看到的,因为自己对hashmap并不是很熟悉。一下贴出网上的hashmap的代码

class Solution {
    public:
vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> res;
        int length = numbers.size();
        map<int,int> mp;
        int find;
        for(int i = 0; i < length; ++i){
        // if have target-numbers[i] return target-numbers[i] ,else create a target-numbers[i] element 
            find=mp[target - numbers[i]]; 
            if( find ){
                res.push_back(find);
                res.push_back(i+1);
                break;
            }
            mp[numbers[i]] = i;
        }
        return res;
    }
};

 

posted @ 2016-04-01 10:24  NeilZhang  阅读(170)  评论(0编辑  收藏  举报