1 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,假設只有一組這樣的數。函數返回這兩個數的下標,且下標1要小於下標2.

解題思路:

   1.因爲要找下標,所以不能對數組先進行排序,這時有兩種方法,一種是用兩個循環遍歷,但是會超時。另一種辦法,使用map;

   2.循環遍歷數組,如果第i個數不在map中,將其加入map。並檢測(target-第i個數)是否在map中,如果在,那麼(target-第i個數)所對應下標即是另外一個數。


代碼:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章