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:
O(n^2)解法 --- 错误解法
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
for (index,value) in nums.enumerated() {
for (index1,value1) in nums.enumerated() {
if (index != index1 && value + value1 == target) {
return [index, index1]
}
}
}
return []
}
}
O(n)解法 --- 正确解法
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var sunDict = [Int : Int]()
for (index, value) in nums.enumerated() {
if let lastIndex = sunDict[target - value] {
return [lastIndex, index]
}
sunDict[value] = index
}
return []
}
}
========================================================
网络答案:
LeetCode 1 Two Sum 解题报告
偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积累可以对以后在对算法中优化带来好处。Ok,今天是我做的第一题Add 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
题目分析
第一次刷LeetCode,太大意了,以为第一题很简单,两层循环,结果 time limit out 超时了。然后看了一眼show tag 尼玛,上档了,果然得用哈希的方法来做。
思路:
根据题目的要求给定一个数组,从中选出两个数,使得两个数的和等于target目标值。
解法如下:
1. 首先将数组的数插入到map中,同时map的key为数组的值,而value等于数组的下标
2. 从map开始遍历,从target减去当前的iter->first 即value1,这里first是键也是原来numbers数组中的值
3. 得到另一个值value2,查看map中是否存在该键,若存在看value1+value2是否等于target
4. 若等于target判断,是否为target的二分之一,因为会出现相同的值,若target为一个value值的两倍,从数组充查找是否存在有两个value,若存在则加入reslut
5. 若不是,则从map中直接取出键所对应的值,按小的在前的顺序放入result,因为map中“值”存放的是实际数组的下标,“键”存放的是实际数组中的值。最后输出result即可。
示例代码
#include<iostream>
#include<vector>
#include<map>
#include<math.h>
#include<algorithm>
using namespace std;
classSolution{
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
map<int,int> nummap;
map<int,int>::iterator i;
for(int i = 0 ;i < numbers.size(); i++)
nummap.insert(make_pair(numbers[i],i+1));//map中key存放numbers数组的值,value存放下标
for(map<int ,int >::iterator iter = nummap.begin(); iter!= nummap.end(); iter++)
{
int value1 = iter->first;
int value2 = target - value1;
i = nummap.find(value2);
if( i != nummap.end())
{
if(value1 + value2 == target)
{
if(value1 == value2)//看找到的值是否为target的二分之一,若是二分之一,必须存在2个才符合要求 {
vector<int>::iterator j;
vector<int>::iterator k = find (numbers.begin(), numbers.end(), value1);
if(k!= numbers.end())//看是否存在两个 {
j = find(k+1, numbers.end(), value1);
if(j!= numbers.end())
{
result.push_back(k-numbers.begin()+1);
result.push_back(j-numbers.begin()+1);
return result;
}
}
}
else//若不是二分之一,说明存在两个不同下标的不同值相加为target,从map中取出他们相应的索引 {
result.push_back(min(nummap[value1],nummap[value2]));
result.push_back(max(nummap[value1],nummap[value2]));
return result;
}
}
}
}
return result;
}
};intmain(){
Solution s1;
int num[] ={0, 2, 4, 0};
vector<int> numbers (num,num+4);
int target = 0;
vector<int> result = s1.twoSum(numbers, target);
for(int i = 0 ;i < result.size(); i++)
{
cout<< result[i]<<endl;
}
return 0;
}