leetcode 第二题两数之和的较优化解决
hash表解法,想要寻找一个性能比较好的解决方式
最开始学习了一下hash表解法,优点是时间复杂度比较小,性能比较好,后面带入常用的双分法优化,从两头往中间插,运行时间提升较为明显
class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums.length<2) return null;
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0;i<=nums.length-1;i++){
int temp = target -nums[i];
if(map.containsKey(temp)) return new int[]{map.get(temp),i};
map.put(nums[i],i);
}
return null;
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums.length<2) return null;
Map<Integer,Integer> map = new HashMap<>();
int temp;
int i = 0,j = nums.length-1;
while(i<=j){
temp = target-nums[i];
if(map.containsKey(temp)) return new int[]{map.get(temp),i};
map.put(nums[i],i);
temp = target-nums[j];
if(map.containsKey(temp)) return new int[]{map.get(temp),j};
map.put(nums[j],j);
j--;i++;
}
return null;
}
}
希望大佬能给出更多的优化意见