[leetcode] 1. Two sum

2017-06-05  本文已影响0人  叶孤陈

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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].  



解题思路

最直观的想法采用暴力搜索法,时间复杂度为O(N*N), 但提交的时候Time Limit Exceeded, 因此暴力搜索不可取。


要想达到O(N)的时间复杂度,根据空间换时间的准则,用哈希表存储数组元素和Index的对应关系,具体代码如下:

class Solution
{
    vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int, int> hash;
    vector<int> res;
    for (int i = 0; i < nums.size(); i++) {
        int temp = target - nums[i];
        if (hash.find(temp) != hash.end()) { //如果在哈希表中查到对应的数字,返回结果
            res.push_back(hash[temp]);
            res.push_back(i);           
            return res;
        }
        hash[nums[i]] = i; //没有查到结果,将数组元素和Index加入哈希表
    }
    return res;
    }
}
上一篇下一篇

猜你喜欢

热点阅读