题目:LeetCode 1.两数之和
LeetCode链接: LeetCode 1.两数之和 https://leetcode-cn.com/problems/two-sum/
审题
边界值问题1:可能不存在两个数为target。 题目重点:只会有对应的一个答案。
解题一
暴力法 遍历所有组合
代码
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(target == nums[i]+nums[j]){
return new int[]{i,j};
}
}
}
throw new IllegalArgumentException("没有满足的数据");
}
}
复杂度
- 时间复杂度O(n²):i循环一遍,j在i的每次循环里有循环了一遍。
- 空间复杂度O(1):不占用存储空间。
易错点
- 暴力法 嵌套的二级循环后循环就是 j=i+1
- IllegalArgumentException异常Argument没有e
解题二
哈希表空间换时间
代码
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 = target - nums[i];
if(map.containsKey(tmp)){
return new int[]{map.get(tmp), i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("没有满足的数据");
}
}
- 时间复杂度O(n):遍历了一次
- 空间复杂度O(n):随n大小变化的哈希表
易错点
- containsKey单词