- 明天补上哈希表使用
完成度
暴力法写了一半
自己的代码
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
}
}
}
}
}
错误
1、不会写数组返回。改正:
return new int[]{i , j}
2、没有考虑到如果没有结果应该返回什么。改正:
throw new IllegalArgumentException("No two sum solution");
题解
方法一:暴力法
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};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
方法二:两遍哈希表
/**
* 两边哈希表
* 第一遍将数组存入Map中
* 第二遍,通过判断差值是否存在于map中,来进行判断
* 时间复杂度O(N):n个元素遍历两次
* 空间复杂度O(N):取决于存入Map的数据
* @param nums
* @param target
* @return
*/
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
//将数组全部存入hashMap中
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
//再次遍历
for (int i = 0; i< nums.length; i++){
int complement = target - nums[i];//获取差值
//通过map.containsKey判断值是否存在
//通过map.get()获取值,并且按照要求,不能重复利用,即!=i
if (map.containsKey(complement) && map.get(complement) != i){
return new int[]{i, map.get(complement)};//返回对应的数
}
}
throw new IllegalArgumentException("No two sum solution");
}