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

[LeetCode] Two Sum

时间:2015-04-20 18:20:27      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/two-sum/

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(n2),代码如下:

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        for (int i = 0; i < numbers.size() - 1; ++i)
        {
            for (int j = i + 1; j < numbers.size(); ++j)
            {
                if (numbers[i] + numbers[j] == target)
                {
                    return vector<int>{i + 1, j + 1};
                }
            }
        }
        
    }
};

直接用暴力解法,在 leetcode 上提交会超时(试了下lintcode,暴力解法可以过掉所有测试用例),那有没有更快的方法呢?我最先想到的是利用哈希表,来记录数组元素值与其下标的映射关系,这样只需要对数组遍历一遍即可,时间复杂度为o(n),空间复杂度也是o(n)。在遍历的同时,完成哈希表的查询与插入。代码如下:

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        unordered_map<int, int> hash;
        for (int i = 0; i != numbers.size(); ++i)
        {
            unordered_map<int, int>::const_iterator itr = hash.find(target - numbers[i]);
            if (itr == hash.cend())
            {
                hash.insert(make_pair(numbers[i], i));
            }
            else
            {
                return vector<int>{itr->second + 1, i + 1};
            }
        }
        
    }
};  

[LeetCode] Two Sum

标签:

原文地址:http://www.cnblogs.com/jianxinzhou/p/4442249.html

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