TwoSum

Problem###

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


Analysis###

關鍵是尋找兩個合適的數
最先以為序列式有序的,結果不是;
然后直接窮舉所用組合,結果會超時;
最后使用HashMap來實現,key = 數的值,value = 數的位置:首先將所有的數與其位置存儲于Map中,然后對于每個數去檢測能和它組合成target的數的位置,如果沒有,就下一個。


Tips###

1:numbers 是無序的!
2:窮舉會超時!:
3:如果Hash搜索的時候是按numbers的順序從前往后找的話,其本身就是index1小,index2大。


Implementation###

package twosum; import java.util.HashMap; public class Solution { public int[] twoSum(int[] numbers, int target) { HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i = 0 ; i < numbers.length ; i++){ map.put(numbers[i], i); } for(int i = 0 ; i < numbers.length ; i++){ int left = target - numbers[i]; if(map.get(left) != null && map.get(left) != i){ int[] indexs = {(i+1),(map.get(left)+1)}; return indexs; } } return null; } }


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容