题目链接:https://leetcode.cn/problems/two-sum/description/?envType=study-plan-v2&envId=top-100-liked
暴力解法
因为 2 <= nums.length <= 10^4,所以可以用两个 for 循环 O(n * n) 的时间复杂度解决问题
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
if(nums[i] + nums[j] == target) return new int[]{i, j};
}
}
return new int[]{0, 0};
}
}
哈希表
只遍历一遍数组,然后遍历过的就存到哈希表中,如果哈希表有满足条件的,就直接返回
class Solution {
public int[] twoSum(int[] nums, int target) {
//用一个变量存储数组nums的长度
int n = nums.length;
//创建一个哈希表h,键值对分别存储数组元素的值和下标
Map<Integer, Integer> h = new HashMap<Integer, Integer>();
//遍历nums数组
for(int i = 0; i < n; i++){
//判断哈希表h的键里是否存在等于target - nums[i]的元素
if(h.containsKey(target - nums[i])){
//如果存在,就用get方法获取这个键对应的值,并返回
return new int[]{h.get(target - nums[i]), i};
}else{
//如果不满足,则加入哈希表,用于后续的判断
h.put(nums[i], i);
}
}
return new int[]{0, 0};
}
}
还剩99题!