给定一个整数数组nums = [2, 7, 11, 15]和目标值target = 9,找出和为目标值的那两个整数的下标
下面是我的代码,有个错误
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0;i < nums.length;i++){
for(int j = i + 1;j < nums.length;j++){
if(nums[i] + nums[j] == target){
return new int[] { i, j };
}
}
}
}
}
百度后找到了大佬的代码,如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException(“No two sum solution”);
}
}
原文链接:https://blog.youkuaiyun.com/qq_42960550/article/details/81637567
对比后发现,我的代码缺少一个返回值(如果if语句不通的话,整个代码是没有返回值的),但是大佬却直接抛出了IllegalArgumentException异常
进阶(哈希)
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-2/
来源:力扣(LeetCode)
如果使用双重for循环,时间复杂度为O(n^2)
其实我有个问题,确认数组中是否存在一个元素,函数本身也要进行循环吗?这样的话最大时间复杂度不应该还是O(n^2)吗?
百度后,大佬的解释是:HashMap的数据结构决定了查找是否存在key最好的时间复杂度为O(1),最坏情况下为O(n)
map中的containsKey(key)方法是判断该key在map中是否有key存在。如果存在则返回true。如果不存在则返回false。
- 初始化一个map
- 遍历 nums,i 为当前下标,每个值都判断map中是否存在 target-nums[i] 的 key 值
- 如果存在,则找到了两个值,返回下标
- 如果不存在,则将当前的 (nums[i],i) 存入 map 中,继续遍历
- 如果nums遍历完都没有结果,则抛出异常