[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 ,如需转载请自行联系原博主。

相关文章
|
11月前
|
存储 算法 安全
LeetCode - #1 Two Sum
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
LeetCode - #1 Two Sum
|
12月前
|
机器学习/深度学习
leetcode - two-sum
leetcode - two-sum
65 0
LeetCode:1. 两数之和 two-sum
LeetCode:1. 两数之和 two-sum
76 0
LeetCode tow Sum 两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
66 0
LeetCode tow Sum 两数之和
|
机器学习/深度学习 Android开发 C++
LeetCode之Two Sum
LeetCode之Two Sum
100 0
|
索引
LeetCode 1:两数之和 Two Sum
题目: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
879 0