The Sum of
Given an array of integers, find the numbers such that they add up to a specific target number.
The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.
You may assume this each input would has exactly one solution.
Input:numbers={2, 7, one, A, target=9
Output:index1=1, index2=2
Start to want to use a double loop, time complexity O (n^2) timeout, see Someone with HashMap, take advantage of HashMap find time as a constant, reduce the complexity of time
Reference: http://blog.csdn.net/jiadebin890724/article/details/23305449
1 Importjava.util.Hashtable;2 Public classSolution {3 Public int[] Twosum (int[] numbers,inttarget) {4 intResult[] =New int[2];5 6Hashtable<integer, integer> nums =NewHashtable<integer, integer>();7 8 for(inti = 0; i < numbers.length; i++){9Integer index =Nums.get (Numbers[i]);Ten if(NULL==index) { One Nums.put (Numbers[i], i); A } -index = Nums.get (Target-numbers[i]); - if(NULL! = Index && Index <i) { theResult[0] = index + 1; -RESULT[1] = i + 1; - Break; - } + } - returnresult; + } A}
The Sum of