https://www.jianshu.com/p/c8da31ee2e51
给定一个整数数组,找出其中两个数相加等于目标值
例如:给定数组及目标值 nums = [2,7,11,15] ,target = 9
因为nums[0] + nums[1] = 2 + 7 = 9
返回[0,1]
利用HashMap
private int[] findData(int[] array,int target){
int[] result={-1,-1};
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<array.length;i++){
map.put(array[i],i);
}
for(int i=0;i<array.length;i++){
int two = target-array[i];
if(map.containKey(two)&&target!=2*two){
result[0]=i;
result[1]=map.get(two);
break;
}
}
retrurn result;
}
本文探讨了在给定整数数组中寻找两个数相加等于目标值的问题,通过使用HashMap实现快速查找,提供了一种高效解决方案。

1619

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



