import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
*功能描述 :两数之和
* @author lkr
* @date 2019/3/5
*/
public class Solution1 {
//暴力法
public static int[] twoSum(int[] nums, int target) {
int[] arr = new int[2];
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
int sum = nums[i] + nums[j];
if(target == sum){
arr[0] = i;
arr[1] = j;
}
}
}
return arr;
}
//一遍哈希表
public static int [] oneHashtable(int[] nums,int target){
Map<Integer,Integer> map = new HashMap();
for (int i=0;i<nums.length;i++){
int value = target - nums[i];
if(map.containsKey(value)){
/*int[] arr = {map.get(value),i};
return arr;*/
return new int[] {map.get(value),i};//为什么map.get(value)在前面?
}
map.put(nums[i],i);
}
throw new IllegalArgumentException("NO TWO SUM SOLUTION");
}
public static void main(String[] args){
int [] nums = {2,7,11,15,9};
int target = 20;
//int [] arr = twoSum(nums,target);
int [] arr = oneHashtable(nums,target);
System.out.println(Arrays.toString(arr));
}
}
转载于:https://www.cnblogs.com/turningli/p/10474374.html