題目:
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,數組中同一個元素不能使用兩遍。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/two-sum
思路:兩次遍歷: * 1、用一個 Map<Integer,List<Integer> 存放數組中每個元素的的值與下標,即 (num,[index1,index2]),因爲數組中可能有多個值相同的元素 * 2、遍歷數組,對指定元素num,看是否存在 target - num 的元素,並獲取其下標值 * 1)如果 鍵爲 target - num 對應的 鏈表中存放的下標數大於等於2 ,則說數組中至少有2個元素的值均爲 target/2 ,返回下標即可 比如[3,3,4,5,4] * * 6 * 2)如果 鍵爲 target - num 對應的 鏈表中存放的下標數爲1 ,則要判斷存放在鏈表中的下標值是否等於當前元素num 的下標,爲了防止 當num == taeget/2 且元素之出現一次的情況 * 比如[3,4,5,1] * 6
public int[] twoSum(int[] nums, int target) {
Map<Integer,List<Integer>> map = new HashMap<>();
//第一次遍歷,記錄下數組中元素與其下標
for(int i=0;i<nums.length;i++){
if(map.containsKey(nums[i])){
map.get(nums[i]).add(i);
}else{
List<Integer> list = new ArrayList<>();
list.add(i);
map.put(nums[i],list);
}
}
int i=0;
int j=0;
int[] result = new int[2];
//第二次遍歷,找到與當前元素 num 之和爲target的另外一個元素的下標
for(;i<nums.length;i++){
if(map.containsKey(target-nums[i])){
List<Integer> list = map.get(target-nums[i]);
if(list.size()>=2){ //如果數組中有兩個及以上的元素 num == target/2 ,則直接獲取其下標即可
result = new int[]{list.get(0), list.get(1)};
break;
}else {
j = list.get(0);
if(i==j){ //爲了應對 [3,4,5,1] 6 情況
continue;
}
result = new int[]{i, j};
break;
}
}
}
return result;
}