两数之和
📃 题目描述
🔔 解题思路
最简单的思路就是穷举,嵌套遍历,不过显然时间复杂度太高:
package com.kami.leetcode.hash_table;
/**
* @Description: TODO
* @author: scott
* @date: 2022年01月26日 9:04
*/
public class Solution_1 {
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};
}
}
}
//不存在这两个数的时候
return new int[0];
}
}
可以通过一个哈希表减少时间复杂度:哈希表的 key 对应元素的值,哈希表的 value 对应元素的下标(因为题目需要返回的就是下标),比如某个元素值为 2,就将这个元素的下标存放在哈希表的 key = 2 的 value 上。这样,我们只需要遍历一遍数组,查看 map 中 target - nums[i] 对应的键值对是否存在(并且还要注意这个数不能是 nums[i] 本身),就能知道有没有元素能和 2 组成 target 了。
package com.kami.leetcode.hash_table;
import java.util.HashMap;
/**
* @Description: TODO
* @author: scott
* @date: 2022年01月26日 9:04
*/
public class Solution_1 {
public int[] twoSum(int[] nums, int target){
if(nums == null || nums.length == 0){
return new int[0];
}
//创建一个HashMap,key: 元素值, value: 元素下标
HashMap<Integer, Integer> hashM = new HashMap<>();
// 处理数组存入 hashM
for(int i = 0; i < nums.length; i++){
hashM.put(nums[i], i);
}
//遍历数组来判断
for(int i = 0; i < nums.length; i++){
// 当前元素 nums[i] + j = target
int j = target - nums[i];
// 在 map 中查找下 j 对应的键值对是否存在, 并且还要注意这个数不能是 nums[i] 本身
if(hashM.containsKey(j) && hashM.get(j) != i){
return new int[] {i, hashM.get(j)};
}
}
return new int[0];
}
}