address
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
My Solution:
public int[] twoSums(int[] nums,int target){ //o(n) int res[] = {0,0}; HashMap<Integer, Integer> map = new HashMap<>(); for(int i=0;i <nums.length;i++){ if(map.containsKey(target - nums[i])){ res[0] = map.get(target - nums[i])+1; res[1] = i+1; map = null; return res; }else if(!map.containsKey(nums[i])){ map.put(nums[i], i); } } map = null; return res; } public int[] twoSum(int[] nums, int target) { //o(n^2) int res[] = {0,0}; for (int i=0;i<nums.length;i++){ res[0] = i+1; for(int j = res[0];j<nums.length;j++){ res[1]=j+1; if(nums[i]+nums[j] == target){ return res; } } } res[0] = 0; res[1] = 0; return res; }
The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).
We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.