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###
關(guān)鍵是尋找兩個(gè)合適的數(shù)
最先以為序列式有序的,結(jié)果不是;
然后直接窮舉所用組合,結(jié)果會(huì)超時(shí);
最后使用HashMap來實(shí)現(xiàn),key = 數(shù)的值,value = 數(shù)的位置:首先將所有的數(shù)與其位置存儲(chǔ)于Map中,然后對(duì)于每個(gè)數(shù)去檢測(cè)能和它組合成target的數(shù)的位置,如果沒有,就下一個(gè)。
Tips###
1:numbers 是無序的!
2:窮舉會(huì)超時(shí)!:
3:如果Hash搜索的時(shí)候是按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; } }