Two Sum

原创 2015年07月08日 15:30:01

描述
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
中文:
给定一个整形数组。如果数组里面有两个数相加等于目标数,返回他们的索引。
索引1必须比索引2小。
必须确保每个输入都有唯一解。
分析:没限制时间复杂度,可以用hash做。
另外,索引是从1开始的,所以要注意。


class Solution {
public:
vector<int> twoSum(vector<int> &num, int target) {
unordered_map<int, int> mapping;
vector<int> result;
for (int i = 0; i < num.size(); i++) {
mapping[num[i]] = i;
}
for (int i = 0; i < num.size(); i++) {
const int gap = target - num[i];
//leetcode题解有错误,两个索引不能相同。
if (mapping.find(gap) != mapping.end()&&mapping[gap]!=i) {
result.push_back(i + 1);
result.push_back(mapping[gap] + 1);
break;//必须有跳出循环。
}
}
return result;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Two Sum算法调试小demo

  • 2017年08月17日 18:01
  • 833B
  • 下载

Two Sum leetcode c++

  • 2015年10月01日 10:47
  • 763B
  • 下载

从今天起,刷题看数据结构算法——leetcode题 two sum

leetcode

【LeetCode-面试算法经典-Java实现】【001-Two Sum(求两个数的和)】

给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。要求:这个函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。请注意一点,你返回的结果(包...

#1 Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number. The...

【Leetcode】1. Two Sum

1. Two Sum Total Accepted: 254411Total Submissions: 1031847Difficulty: Easy Given an array...

29. Divide Two Integers/49. Group Anagrams/96. Unique Binary Search Trees/560. Subarray Sum Equals K

Divide Two Integers Problem Description Implementation29. Divide Two IntegersProblem DescriptionDivi...

leetcode No.1 Two Sum

题意: 给定一个数组, 给定一个目标数, 找出数组中和等于目标数的两个数的位置。 题目相对简单。但是第一次接触leetcode觉得挺新鲜,选择C++语言答题后编辑框中是这样的: class Sol...

DAY1:leetcode #1 Two Sum

1、Two Sum Given an array of integers, return indices of the two numbers such that they add up to a...

Leetcode-1 Two Sum(Java) -by zzy

Problems: Given an array of integers, find two numbers such that they add up to a specific target n...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Two Sum
举报原因:
原因补充:

(最多只允许输入30个字)