[leetcode] 1. Two sum

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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容