这题是说存在一个整数数组,要求找到两个数字相加之后可以和目标整数相等。题目里面存在一个问题就是这个数组是无序的,另外就是这个数组中可能存在两个相等的数字,要求我们返回这个数在数组中对应的位置,提示这个就是说要对index加1之后才是位置。
解法1:将这个数组排序,由于题目收欧诺个说过
each input would have exactly one solution.也就是说有的话就只可能有一个解法,所以我们可以先对数组排序然后定义两个指针寻找既可。但是这个时间复杂度有O(nlogn)解法2:推荐解法,我们想到的是将这个数组首先存入HashMap中,利用HashMap搜索数据时间复杂度为1的特性查找数据,思路是做一次for循环,每次都把本次的数据放入hashmap,然后寻找是否存在满足条件的一对数。注意存放时如下所示Map<数值,索引值>。
import java.util.HashMap; import java.util.Map; /** * Created by Cookies on 2015-01-04. * 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 */ public class TwoSum { public static void main(String[] args){ int[] values = new int[3]; values[0] = 3; values[1] = 3; values[2] = 4; int[] result = twoSum(values,6); System.out.print("0:"+result[0]+"1:"+result[1]); } public static int[] twoSum(int[] numbers,int target){ if(numbers==null || numbers.length<2) return null; Map<Integer,Integer> map = new HashMap<>(); for(int i=0;i<numbers.length;i++){ if(map.get(numbers[i])==null){ map.put(numbers[i],i); } int temp = target-numbers[i]; if (map.get(temp)!=null && map.get(temp)!=i){ int a = map.get(temp); int[] values = new int[2]; values[0] = a; values[1] = i; return values; } } return null; } }