问题描述:
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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
中文大意:
输入数组,以及一个target值,如果num[i]+num[j]=target,并且i!=j,则返回i,j。
解题思路:
1.暴力。复杂度O(n^2),超时。
2.hash。用哈希表存储target-num[i]作为key值,i为value值。取num[i],返回的i即为对应的j值。复杂度O(n)。
3.先排序,后左右夹逼。排序O(nlogn),夹逼O(n),最终O(nlogn)。但是排序会影响原来的数组顺序,对于返回原数组值可行,对于返回对应下标不可行。
代码:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class L001_Two_Sum {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String str = in.nextLine();
int target = in.nextInt();
String[] str1 = str.split(" ");
int[] nums = new int[str1.length];
for(int i = 0;i<str1.length;i++){
nums[i]=Integer.parseInt(str1[i]);
}
L001_Two_Sum ts = new L001_Two_Sum();
int[] res = ts.twoSum(nums,target);
System.out.println(res[0]+" "+res[1]);//输出两个下标值
System.out.println(nums[res[0]]+" "+nums[res[1]]);//输出对应的数值
}
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hm = new HashMap<Integer,Integer>();
//只会有一种解
for(int i = 0;i<nums.length;i++)
hm.put(target-nums[i],i);
for(int j = 0;j<nums.length;j++){
Integer v = hm.get(nums[j]);//value值,此处要用Integer不能用int,因为下面要和null比较
if(v!=null&&v!=j){//null一定要写在前面,否则会引起NullPointerException异常
return new int[]{j,v};
}
}
return null;
}
}