暴力法:
最简单的方法无非就是暴力破解,两层for循环依次遍历即可
时间复杂度为o(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];
}
}
哈希法:
有没有什么办法可以降低时间复杂度呢
由于target是固定的,我们经过第一层遍历的时候已经确定了一个加数,另一个加数即可通过target-nums[i]确定。
确定一个数是否存在或者是否出现过不妨想到用哈希法
由于是数字 容量无限大,所以不采用固定长度的数组,而是使用hashmap或者hashset
我们需要返回数组的下标,因此哈希表需要同时存储数值和下标,因此采用hashmap的数据结构
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
if(nums == null || nums.length == 0){
return res;
}
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int temp = target - nums[i];
if(map.containsKey(temp)){
res[1] = i;
res[0] = map.get(temp);
}
map.put(nums[i], i);
}
return res;
}
总结:
哈希表是个很好用的东西,我们需要了解什么能用,并且采用什么样的数据结构。