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
Analysis:
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).
With the brute force solution method, the time complexity is high, two times for loop, but the method is easy to think.
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.
Use HashMap to record the required Val for the traversed numbers, and then return to index, with little time complexity.
Answer:
1. Brute Force Solution:
Public classSolution { Public int[] Twosum (int[] Nums,inttarget) { int[] res =New int[2]; for(inti=0; i<nums.length; i++) { for(intj=i+1; j<nums.length; J + +) { intsum = nums[i] +Nums[j]; if(Sum = =target) {res[0] = i + 1; res[1] = j + 1; Break; } } } returnRes; }}
2. HashMap ingenious Solution.
Public classSolution { Public int[] Twosum (int[] Nums,inttarget) { int[] res =New int[2]; HashMap<integer, integer> map =NewHashmap<integer, integer>(); for(inti=0; i<nums.length; i++) { if(Map.containskey (Nums[i])) {res[0] = Map.get (nums[i]) + 1; res[1] = i + 1; } Else{map.put (target-Nums[i], i); } } returnRes; }}
Leetcode--Double Sum