[LintCode] 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 tw.

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.

 Notice

You may assume that each input would have exactly one solution

Example

numbers=[2, 7, 11, 15], target=9

return [1, 2]

Challenge 

Either of the following solutions are acceptable:

  • O(n) Space, O(nlogn) Time
  • O(n) Space, O(n) Time

LeetCode上的原题,请参见我之前的博客Two Sum

class Solution {
public:
    /*
     * @param numbers : An array of Integer
     * @param target : target = numbers[index1] + numbers[index2]
     * @return : [index1+1, index2+1] (index1 < index2)
     */
    vector<int> twoSum(vector<int> &nums, int target) {
        unordered_map<int, int> m;
        for (int i = 0; i < nums.size(); ++i) m[nums[i]] = i;
        for (int i = 0; i < nums.size(); ++i) {
            int t = target - nums[i];
            if (m.count(t) && m[t] != i) {
                return {i + 1, m[t] + 1};
            }
        }
        return {};
    }
};

本文转自博客园Grandyang的博客,原文链接:两数之和[LintCode] Two Sum ,如需转载请自行联系原博主。

相关文章
|
6月前
|
C++
【PTA】L1-046 整除光棍(C++)
【PTA】L1-046 整除光棍(C++)
73 1
LeetCode:1. 两数之和 two-sum
LeetCode:1. 两数之和 two-sum
107 0
LeetCode tow Sum 两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
90 0
LeetCode tow Sum 两数之和
PTA 7-4 素数等差数列 (20 分)
2004 年,陶哲轩(Terence Tao)和本·格林(Ben Green)证明了:对于任意大的 n,均存在 n 项全由素数组成的等差数列。
121 0
|
索引
LeetCode 1:两数之和 Two Sum
题目: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
914 0