題目
給出一個整數(shù)數(shù)組,請在數(shù)組中找出兩個加起來等于目標(biāo)值的數(shù)骤视,
你給出的函數(shù)twoSum 需要返回這兩個數(shù)字的下標(biāo)(index1鞍爱,index2),需要滿足 index1 小于index2.专酗。注意:下標(biāo)是從1開始的
假設(shè)給出的數(shù)組中只存在唯一解
例如:
給出的數(shù)組為 {20, 70, 110, 150},目標(biāo)值為90
輸出 index1=1, index2=2
示例1
輸入
[3,2,4],6
輸出
[2,3]
思路
- 剛剛開始想用排序睹逃,二分方,但是返回的是索引祷肯,所以會造成索引下標(biāo)發(fā)生變化不可行
- 最簡單的就是暴力沉填,兩個循環(huán)解決
- 既然索引下標(biāo)發(fā)生變化,就把下標(biāo)和值一起記錄
hash
import java.util.*;
public class Solution {
/**
*
* @param numbers int整型一維數(shù)組
* @param target int整型
* @return int整型一維數(shù)組
*/
public int[] twoSum (int[] numbers, int target) {
// write code here
int length = numbers.length;
// key:值 value 下標(biāo)
HashMap<Integer,Integer> targetMap = new HashMap<>(length);
int[] result = new int[2];
for(int i = 0; i< length; i++){
int temp = numbers[i];
if(targetMap.containsKey(target - temp)){
result[0] = targetMap.get(target - temp)+1;
result[1] = i+1;
return result;
}
targetMap.put(temp, i);
}
return result;
}
}
數(shù)組循環(huán)
/**
*
* @param numbers int整型一維數(shù)組
* @param target int整型
* @return int整型一維數(shù)組
*/
public int[] twoSum (int[] numbers, int target) {
// write code here
int[] result = new int[2];
int length = numbers.length;
for(int i = 0; i< length-1; i++){
for(int j = i + 1; j< length; j++){
int first = numbers[i];
int second = numbers[j];
if(first + second == target){
result[0]= i+1;
result[1]= j+1;
}
}
}
return result;
}