题目来源:牛客网NC61
给出一个整型数组 numbers 和一个目标值 target,请在数组中找出两个加起来等于目标值的数的下标,返回的下标按升序排列。
(注:返回的数组下标从1开始算起,保证target一定可以由数组里面2个数字相加得到)
数据范围:2≤len(numbers)≤10*5, −10≤numberssi≤10*9,0≤target≤10*9
要求:空间复杂度 O(n),时间复杂度 O(nlogn)
空白模板如下:
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
public int[] twoSum (int[] numbers, int target) {
// write code here
}
}
测试范例:
输入:[3,2,4],6
返回值:[2,3]
说明:因为 2+4=6 ,而 2的下标为2 , 4的下标为3 ,又因为 下标2 < 下标3 ,所以返回[2,3]
解题过程(个人):
第一解法:
非哈希法:遍历所有元素,与taget匹配直到结果相等:
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
public int[] twoSum (int[] numbers, int target) {
// write code here
if(numbers.length<2){
throw new IllegalArgumentException("no solution");
}
for (int c=0;c<numbers.length;c++){
for(int c1=c+1;c1<numbers.length;c1++){
if(numbers[c]+numbers[c1]==target){
return new int[]{c+1,c1+1};
}
}
}
throw new IllegalArgumentException("no solution");
}
}
运行结果:超时
第二解法:
使用HashMap匹配结果:
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
public int[] twoSum (int[] numbers, int target) {
// write code here
if(numbers.length<2){
throw new IllegalArgumentException("no solution");
}
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
for (int c=0;c<numbers.length;c++){
if(hm.containsKey(target-numbers[c])){
return new int[]{hm.get(target-numbers[c])+1,c+1};
}
else{
hm.put(numbers[c],c);
}
}
throw new IllegalArgumentException("no solution");
}
}
运行结果:通过