一堆数字里面找出相加之和等于目标数字的下标
说明:
target:目标和 8
source:数字集合{1,2,3,4,4,5}
目标 获取任意一对满足target = A + B,其中A,B的下标
要求:复杂度为O(n)
这个题目有很多中方法,但是目前能想到最好的就是使用哈希表去做。
代码
/**
*@Date 2019/3/14
*@Function 给出一个target数字,求在数组中两个相加结果和为target的数字下表
*@Author Christ
*/
//复杂度为O(n)
public static List<Integer> getTheTargetNumberIndex((List<Integer> source , Integer target){
//存放结果数组,当没找到时,返回{- 1,-1}
List<Integer> resultList = new List<Integer>();
resultList .add(-1);
resultList .add(-1);
//对数据进行校验
if(source == null || target == null){
return resultList;
}
//把数组放到map里面,因为map查的速度快,底层是哈希算法,复杂度 --- 1
Map<Integer,Integer> sourceMap = new Map<Integer,Integer>();
for (Integer i = 0; i < source.size() -1 ; i++) {
//保证当数组里面有相同数字,比如target = 8, source{1,3,4,4,5},那么4,4就满足。避免map的key唯一的问题
if (sourceMap.size() > 0 && sourceMap.containsKey(source[i]) && target == source[i] * 2) {
resultList.add(i);
resultList.add(sourceMap.get(source[i]));
return resultList;
}else{
sourceMap.put(source[i],i);
}
}
//利用target - source[i]获得新的newTarget,然后判断newTarget是否在map的key值里面存在
for (Integer i = 0; i < source.size() -1 ; i++) {
Integer templateResult = target - source[i];
if (sourceMap.containsKey(templateResult) && target != templateResult * 2) {
resultList.add(i);
resultList.add(sourceMap.get(templateResult));
//找一对数据
return resultList;
}
}
}
测试代码
测试用例
1,target = 8,source={1,2,3,4,4,5};预期返回结果为 resultList 4,3
2,target = 8,source={1,2,3,3,4,5};预期返回结果为 resultList 5,3
3,target = 8,source={4,4,4,4,4,4};预期返回结果为 resultList 2,1
4,target = 8,source={1,1,1,1,1,1};预期返回结果为 resultList -1,-1
5,target = 8,source=null;预期返回结果为 resultList -1,-1
6,target = null,source=null;预期返回结果为 resultList -1,-1
7,target = null,source={1,2,3,3,4,5};预期返回结果为 resultList -1,-1
经过测试,结果都符合预期。
如有错误,欢迎指出。一起进步!