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
The problem is to find the subscript of the given value in a set of arrays.
1. You can use the Java sorting algorithm, and then declare two pointers, one end, if two pointers point to and greater than target, the tail pointer--, conversely, the head pointer + +; time complexity O (NLOGN);
2. Use HashMap, space change time, time complexity is O (n). Key Save Target-nums[i],value Save subscript. Then iterate over the array.
Public classSolution { Public int[] Twosum (int[] Nums,inttarget) {HashMap<Integer,Integer> map=NewHashmap<integer,integer>(); int[] res=New int[2]; for(inti=0;i<nums.length;i++){ if(Map.containskey (Nums[i])) {res[0]=Map.get (Nums[i]); res[1]=i+1; returnRes; }Else{map.put (target-nums[i],i+1); } } returnRes; }}
The Sum of