Two sum 两个数相加
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
第一种:暴力
第二种:排序,然后找
第三种:哈希表法
java:第一遍将数字变为哈希表的key,第二遍直接找到哈希表中的key是否存在。
public static int[] twoSum1(int[] nums, int target){ //基于哈希表 int j; int i; HashMap<Integer,Integer> mymap = new HashMap<Integer, Integer>(); for( i = 0 ; i < nums.length ;i ++){ mymap.put(nums[i],i); } for( i = 0 ; i < nums.length ; i++){ j = target - nums[i]; if(mymap.get(j)!=null && mymap.get(j)!=i){ int arr[] = new int[2]; arr[0] = i; arr[1] = mymap.get(j); return arr; } } return null; }
java 更好的写法2:
一边放入哈希表一边看是否已经存在答案
int j; int i; int arr[] = new int[2]; HashMap<Integer,Integer> mymap = new HashMap<Integer, Integer>(); for( i = 0 ; i < nums.length ;i ++){ if(mymap.containsKey(target - nums[i])){ arr[0] = i; arr[1] = mymap.get(target - nums[i]); return arr; } mymap.put(nums[i],i); } return null;