1. 两数之和
hash表
暴力解法O(n2)
需要注意,暴力的起始点两个数不能从同一个位置开始暴力。
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length - 1; i ++) {
for(int j = i + 1; j < nums.length; j ++) {
if(nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[]{0, 0};
}
}
hash表存储O(n)
每次查找hash表中是否有匹配的数据,如果没有那么把需要匹配的值放入hash表中。
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i ++) {
int tmp = map.getOrDefault(nums[i], -1);
if(tmp == -1) {
map.put(target - nums[i], i);
}
else {
return new int[] {tmp, i};
}
}
return new int[] {0, 0};
}
}