题目
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/two-sum
我看到题的第一反应是用双重for循环
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] index = new int[2];
for(int i = 0;i < nums.length - 1;i++){
int a = target - nums[i];
for(int j = i + 1; j < nums.length; j++){
if(a == nums[j]){
index[0] = i;
index[1] = j;
break;
}
}
}
return index;
}
}
直接就运行成功了,想着太简单了,然后看了结果运行了33ms 我翻开评论区看了下大佬的解题思路,直接震惊了,运行时长3ms,
然后我看了大佬的代码又对自己的代码进行修改,原理是根据hashmap查找
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] index = new int[2];
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length;i++){
if(hash.containsKey(target - nums[i])){
index[1] = i;
index[0] = hash.get(target - nums[i]);
return index;
}
hash.put(nums[i],i);
}
return index;
}
}
运行结果
这里有个坑 hash.put(nums[i],i) 必须写在后面,不然如果数组中的值有重复的时候 当使用hash.get()时,永远只会取出第一个值的下标。
有兴趣的大佬可以加入qq群454753313来一起讨论学习交流。