这是leedcode里最老的一道题,知道两数的和然后从一个无序的int数组中找到这两个数。一开始用两层for暴力查找果断超时了。然后修改了一下,打算排序后用二分查找第二个加数,但是要对数组进行排序,记录下每个元素的位置,也很麻烦。于是我就想到了HashMap进行查找。
使用HashMap进行查找
Map中 KEY为数组元素值,VALUE为index,这样可以迅速查找到某一元素值是否存在,和找到对应的index。代码如下:
public static int[] twoSum2(int[] numbers, int target) {
HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
int[] res={-1,-1};
int num = numbers.length;
for(int i=0;i<num;i++){
mp.put(numbers[i],i);
}
for(int j=0;j<num;j++){
int ser = target-numbers[j];
if(mp.containsKey(ser)){
res[0]=j+1;
res[1]=mp.get(ser)+1;
if(res[0]==res[j]||res[0]>res[j]) continue;
return res;
}
}
return res;
}
Update 2015/07/22: 这次做的是历遍keySet,但是这样不如历遍原数组方便,历遍原数组可以保证顺序,不许判断两个index大小和是否有重复
public class Solution {
public int[] twoSum(int[] nums, int target) {
int [] res = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i=0; i<nums.length; i++){
if (map.containsKey(nums[i]) && nums[i]*2 == target){
res[0] = map.get(nums[i]);
res[1] = i+1;
return res;
}
map.put(nums[i], i+1);
}
for (int key: map.keySet()){
if (map.containsKey(target - key)){
if(map.get(key) < map.get(target - key)){
res[0] = map.get(key);
res[1] = map.get(target - key);
}else{
res[1] = map.get(key);
res[0] = map.get(target - key);
}
}
}
return res;
}
}
本文介绍了一种利用HashMap高效解决LeetCode中最古老的问题之一:从无序整数数组中找到两个数,使得它们的和等于给定的目标值。通过将数组元素映射到其索引,作者提出了一种简洁且高效的解决方案,避免了传统的双层for循环带来的性能瓶颈。
588

被折叠的 条评论
为什么被折叠?



