题解 | #两数之和#
两数之和
https://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
import java.util.*;
public class Solution {
/**
*
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
public int[] twoSum (int[] numbers, int target) {
// write code here
int[] res = new int[2];
//哈希表中,存元素和下标,然后遍历当前元素,找对应的差值
HashMap<Integer,Integer> hm = new HashMap<>();
for(int i = 0;i<numbers.length;i++){
int complement = target - numbers[i];
if(hm.containsKey(complement)){
//这里面包含了顺序,肯定当前元素是才开始的,在后面
//插值是前面就已经加入的,这个在前面
res[0] = hm.get(complement)+1;
res[1] = i+1;
return res;
}else{
hm.put(numbers[i],i);
}
}
return res;
}
}
查看24道真题和解析
韶音科技公司氛围 665人发布