01_两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**
代码
利用hashMap进行快速的查找操作,平均查找效率O(logn)
static class Solution {
public static int[] twoSum(int[] nums, int target) {
int[] result=new int[2];
Map<Integer,Integer> m=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
if(m.containsKey(target-nums[i])){
result[0]=i;
result[1]=m.get(target-nums[i]);
return result;
}else {
m.put(nums[i],i);
}
}
return result;
}
}
上述代码较为容易理解,下面是排名靠前的大佬代码
class Solution {
public int[] twoSum(int[] nums, int target) {
int indexArrayMax = 2047;
int[] indexArray = new int[indexArrayMax + 1];
int diff = 0;
for (int i=0; i<nums.length; i++) {
diff = target - nums[i];
if (indexArray[diff & indexArrayMax] != 0) {
return new int[]{indexArray[diff & indexArrayMax] - 1, i};
}
indexArray[nums[i] & indexArrayMax] = i + 1;
}
return null;
}
}
直接利用数组的随机存取就可以获得对应的值。其实indexArrayMax 可以为任何数,因为**&操作相当于对一个数的二进制进行截取,所以一般indexArrayMax会设为2^n-1**,当然,为了让空间占用不是那么高,所以会设置到一个较小的范围,并且该程序会存在些许隐藏bug,即当原数组中超过了indexArrayMax+1的数目时,有概率会覆盖前面已经存在的数字。
**
挖坑中……
Java中有关hash的面试题!!!!
**