给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
力扣 地址: https://leetcode-cn.com/problems/two-sum
拿到题的第一眼马上能想到的方法通过两层遍历得到对应的下标数据.
这样下来最坏的时间的时间复杂度是o(2n).
先看这种解法.
public static int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
for(int j=0;j<nums.length;j++){
if(nums[j]==target-nums[i]){
return new int[]{i,j};
}
}
}
return null;
}
这种解法相当于是一个暴力解法.时间最坏复杂度为o(2n).
Map<Integer,Integer> numMaps= new HashMap();
for (int i=0;i< nums.length;i++) {
numMaps.put(nums[i],i);
}
for(int i=0;i<nums.length;i++){
int leftNum=target-nums[i];
if(numMaps.containsKey(leftNum)
&& numMaps.get(leftNum)!=i){
return new int[]{i,numMaps.get(leftNum)};
}
}
return null;
通过Map contains的o(1).虽然在最坏场景下.仍旧是o(2n),但平均时间复杂度肯定相比第一种解法要优化得多.