Question:
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
Question Tags:
Array, Hash Table
New Words:
Add up to: Total
The plural of indices:index
Zero-based: zero-based
Solution Ideas:
Idea One:
Two-layer traversal: For a number in an array, sum it to a certain number in the future, and if it is equal to the target, you can determine if the two values are the one you are looking for.
Idea two:
Hashmap--value-key method: A+b=target, that is, whether a and target-a are in this array,
Traverse to determine if there is a value in the array in the map target-a, if not, then the key of a is stored in value as a key to the map,
If there is, then the request for a, a, a must come out. The index value to be evaluated is the index value of a, b
Both of these methods ensure that the INDEX1<INDEX2 is available.
Solution Java Code:
Importjava.util.Arrays;ImportJava.util.HashMap;ImportJava.util.Map; Public classTwosum { Public Static voidMain (string[] args) {int[] numbers={2, 7, 11, 15}; inttarget = 9; int[] Twosum =twosum (Numbers,target); System.out.println ("The sum indices is" + twosum[0] + "and" + twosum[1]); int[] twoSum2 =twoSum2 (Numbers,target); System.out.println ("The sum indices is" + twosum2[0] + "and" + twosum2[1]); }
Idea 1 Public Static int[] Twosum (int[] numbers,inttarget) { inti,j,sum; int[] Indices =New int[2]; Outfor: for(i=0;i<numbers.length;i++){ for(J=i+1;j>i && j<numbers.length;j++) {sum= numbers[i]+Numbers[j]; if(Sum = =target) {indices[0]=i+1; indices[1]=j+1; Breakoutfor; } } } returnindices; }
Idea 2 Public Static int[] twoSum2 (int[] numbers,inttarget) { int[] Indices =New int[2]; Map<Integer,Integer> map =NewHashmap<integer,integer>(); for(inti=0;i<numbers.length;i++){ if(Map.containskey (target-Numbers[i])) {indices[0]=map.get (target-Numbers[i]); indices[1]=i+1; Break; } map.put (Numbers[i],i+1); } returnindices; }}
"Leetcode" algorithm practicing---the Sum of