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, target=9
Output: index1=1, index2=2
A solution to the problem
Brute force enumeration, Time complexity O (n^2), and because Target is a two-digit number, it is only possible to use the brute-force enumeration method even if the array is ordered.
Two ways to solve problems
Since the time required to traverse the graph is relatively fixed, you can use HashMap, with the contents of the array as key, and the array subscript as value, so that the time complexity is O (n).
Therefore, the first step: the array elements into the hashmap inside, the second step: for numbers[] Each value, with Target-numbers[i] in the graph to traverse, if found that there is such a value, and such a value is not numbers[i] corresponding to the node itself, then , the traversal ends.
The Java code is as follows:
1 ImportJava.util.HashMap;2 Public classSolution {3 Static Public int[] Twosum (int[] numbers,inttarget) {4 int[] a={0,0};5Hashmap<integer,integer> map=NewHashmap<integer,integer>();6 for(inti=0;i<numbers.length;i++){7 Map.put (Numbers[i], i);8 }9 for(inti=0;i<numbers.length;i++){Ten intgap=target-Numbers[i]; One if(Map.get (GAP)! =NULL) &&map.get (GAP)! =i) { AA[0]=i+1; -A[1]=map.get (GAP) +1; - Break; the } - } - returnA; - } +}
Java for Leetcode 001 the Sum of