[leetcode]Two Sum
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
思路1 : 两层遍历: 对每一个元素查找剩余元素中的是否有满足条件的余数,时间复杂度为O(n^2)
思路2 :先遍历一遍数组,记录每个数组元素及下标,第二遍遍历的时候,就可以判断数组中是否包含余数了。时间复杂度为O(n),两次遍历
代码如下:
public class Solution { public int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; if(numbers == null || numbers.length < 2) return result; Map<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i = 0; i < numbers.length ; map.put(numbers[i],i + 1),i++); for(int i = 0 ; i < numbers.length; i++){ if(map.containsKey(target - numbers[i]) && map.get(target - numbers[i]) != i + 1){ result[0] = i + 1; result[1] = map.get(target - numbers[i]); break; } } return result; } }
优化:
思路3: 一边遍历,时间复杂度O(n)
在遍历的时候,map的key记录元素的余数,value记录元素下标,当查到map包含某个元素时,即找到第一对满足条件的两个数,同理,该法一边遍历可以找到所有的元素对
public class Solution { public int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; if(numbers == null || numbers.length < 2 ) return result; Map<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i = 0; i < numbers.length; i++){ if(map.get(numbers[i]) == null){ map.put(target - numbers[i], i + 1); }else{ result[0] = map.get(numbers[i]); result[1] = i + 1; } } return result; } }