传送门:https://leetcode.cn/problems/two-sum/description/?envType=study-plan-v2&envId=top-100-liked
题意就是让我们找到两个和为target
的数的下标。
第一眼思路我们可以暴力枚举两个数然后判断条件,时间复杂度为
然后我们不难想到可以用hash表来做,用原数组的值作为hash表的键,下标作为hash表的值,这样假设第一个数为
参考代码:
java
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> num = new HashMap<>();
for(int i = 0;i < nums.length;i++) {
num.put(nums[i], i);
}
for(int i = 0;i < nums.length;i++) {
int other_num = target - nums[i];
if(num.get(other_num) != null && i != num.get(other_num)) {
return new int[]{i, num.get(other_num)};
}
}
return null;
}
}
Hash表推荐文章:https://www.hello-algo.com/chapter_hashing/hash_map/