Hash map
利用hashmap,将每个元素值作为key,数组索引作为value存入hashmap,然后遍历数组元素,在hashmap中寻找与之和为target的元素。
·时间复杂度O(n),空间复杂度O(n)。
实现1:public class Solution {
public int[] twoSum(int[] numbers, int target) {HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = new int[2];
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(numbers[i])) {
int index = map.get(numbers[i]);
result[0] = index+1 ;
result[1] = i+1;
break;
} else {
map.put(target - numbers[i], i);
}
}
return result;}
实现2:
public class solution{
public int[]twoSum(int[]numbers, int target)
{
Hashmap<Integer,Interger>num=new Hashmap();
for(int i=0;i<numbers.length;i++){
num.put(number[i],i);
}
for (int i=0; i<numbers.length;i++){
Interger index2=num.get(target-number[i]);
if (interger index!=null&&index!=i){
return new int[]{i+1,index2+1};
}
return null;
}
}