美文网首页
LeetCode Two Sum

LeetCode Two Sum

作者: codingcyx | 来源:发表于2018-03-27 16:43 被阅读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].
vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        map<int, int> hash;
        for(int i = 0; i<nums.size(); i++){
            if(hash.count(target - nums[i])){
                res.push_back(hash[target-nums[i]]);
                res.push_back(i);
                break;
            }
            hash[nums[i]] = i;
        }    
        return res;
    }

使用map可以提高查找效率,使查找在近似O(n)内完成,避免了暴力查找O(n²)的复杂度。
上面的程序是边查找边在map中加数据的,也可以全部加进去之后再查找。

相关文章

网友评论

      本文标题:LeetCode Two Sum

      本文链接:https://www.haomeiwen.com/subject/yjsscftx.html