1. 程式人生 > >[Leetcode] two sum 兩數之和

[Leetcode] two sum 兩數之和

cnblogs specific 等於 numbers 順序 思路 one bre end

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.

[Leetcode] two sum 兩數之和