题目
题目链接
https://leetcode.cn/problems/two-sum/?envType=study-plan-v2&envId=top-100-liked
解题思路
利用哈希表来解题,类似于滑动窗口的解法。
$$时间复杂度为O(n)$$
相关代码
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hash = new HashMap<>();
int a[] = new int[2];
for(int i=0;i<nums.length;i++){
if(hash.get(target-nums[i])==null) hash.put(nums[i],i);
else {
a[0] = hash.get(target-nums[i]);
a[1] = i;
}
}
return a;
}
}