[Leetcode] 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

题意:给定一个数,在数列中找到两数的下标,它们的和等于这个数。

思路:暴力法是,每两个组成一对,判断其和是否等于target,时间复杂度为O(n^2)。我们可以采用关联容器unordered_map,先将数组中每个数和其下标存入map中,然后,遍历数组中的元素,看target于元素值之差是否在map中,若在则记下两者下标就行。因为是遍历数组是从头开始的,所以不用考虑下标的大小顺序。但有一点用注意的是如:[3,2,4],target=6,这种情况时,在map中查找时要注意出去当前元素值,若不除去,当前值为3,在map中查找时,也找到3,这样就不对了。

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target) 
 4     {
 5         unordered_map<int,int> m;
 6         vector<int> res;
 7 
 8         for(int i=0;i<numbers.size();i++)
 9         {
10             m[numbers[i]]=i;
11         }    
12 
13         for(int i=0;i<numbers.size();i++)
14         {
15             int val=target-numbers[i];
16             if(m.find(val) !=m.end()&&m[val] !=i)
17             {
18                 res.push_back(i+1);
19                 res.push_back(m[val]+1);
20                 break;
21             }  
22             
23         }
24         return res;
25     }
26 };

注:因为牛客网的题目的下标是从1开始的,所以存入res时,下标要加1.

原文地址:https://www.cnblogs.com/love-yh/p/7214272.html