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, A, target=9
Output:index1=1, index2=2
Solution:
1. O (n2) runtime, O (1) space–brute Force:
The brute force approach are simple. Loop through each element x and the find if there is another value, the Equals to target–x. As finding another value requires looping through the rest of the array, its runtime complexity is O(n2).
2. O (n) runtime, O (n) space–hash table:
We could reduce the runtime complexity of looking up a value to O(1) using a hash map, maps a value to it in Dex.
1 Public classSolution {2 Public int[] Twosum (int[] Nums,inttarget) {3Map<integer, integer> HM =NewHashmap<integer, integer>();4 int[] result =New int[2];5 intLength =nums.length;6 for(inti = 0; i < length; i++) {7 intleft = target-Nums[i];8 if(Hm.get (left)! =NULL) {9Result[0] = Hm.get (left) + 1;TenRESULT[1] = i + 1; One}Else { A Hm.put (Nums[i], i); - } - } the returnresult; - } -}
3. O (Nlogn) runtime, O (1) space-binary Search
Similar as solution 1, but with binary search to find INDEX2.
4. O (nlogn) runtime, O (1) space-two pointers
First, sort the array in ascending order Vwhich uses O (NLOGN).
Then, the right pointer starts from biggest number and the left pointer starts from smallest number. If the sum is greater than the target number, move the right pointer. If the sum is smaller than the target number, move the left pointer.
The sum solution