
引入HashMap,将数组中的元素转存到HashMap中。Hash表的特性以O(1)的时间复杂度判断key=target - nums[i]是否存在
class Solution {
public int[] twoSum(int[] nums, int target) {
//hash优化
//HashMap key-value 元素-下标
int len = nums.length;
Map<Integer,Integer> hash = new HashMap<>();
for(int i = 0 ; i < len; i++) {
hash.put(nums[i],i);
}
for(int i = 0 ; i < len; i++) {
int x = target - nums[i];
if(hash.containsKey(x) && i != hash.get(x)) {
return new int[]{i,hash.get(x)};
}
}
return null;
}
}
7242



被折叠的 条评论
为什么被折叠?



