一道小算法題,在一堆數字裏面找出相加之和等於目標數字的下標

一堆數字裏面找出相加之和等於目標數字的下標

說明:
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

經過測試,結果都符合預期。

如有錯誤,歡迎指出。一起進步!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章