就像英语里面永远的abandon一样,LeetCode永远的两数之和~
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。
本题的意思很明显,给出一组数组,求出两数之后为target的两个元素索引下标。
题解一(暴力解法)
第一想法暴力解题,两个循环出所有数据分别相加,得到数组索引。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(target ==nums[i]+nums[j]){
result[0]=i;
result[1]=j;
return result;
}
}
}
return null;
}
}
问题很明显,时间复杂度为O(n²),比较耗时。
题解二:
我们由题解一可以得到一些获取的数据是重复获取的,那我们可以将这些重复的元素值为Key,索引为Value,放入map中,每次先查询是否存在,存在直接返回。
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
int[] result = new int[2];
for(int i=0;i<nums.length;i++){
int num =target-nums[i];
Integer numIndex = map.get(num);
if(null !=numIndex){
result[0] =numIndex;
result[1] =i;
return result;
}else {
map.put(nums[i],i);
}
}
return null;
}
}