leetcode热题系列第一题
1. 两数之和
题目描述:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
思路:
- 常规解法每求一个数都要是否符合题目要求的另外一个数。这样时间复杂度O(n^2).
- 我们发现,时间复杂度主要是为了寻找另外一个数字,所以我们可以利用hashmap这个结构 在O(1)内找到另外一个数字。
github地址:
https://github.com/CLFlemon/LeetcodeHot100
代码:
package Hot001;
import java.util.HashMap;
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
HashMap<Integer,Integer> hashMap = new HashMap<>();
for(int i = 0; i< nums.length;i++){
hashMap.put(nums[i],i); //注意 我们要通过hashMap的get(key)得到坐标i 注意不要弄反了
}
for(int i = 0;i<nums.length;i++){
int temp = target - nums[i]; //目标数
if(hashMap.containsKey(temp) && hashMap.get(temp) != i){ //存在 保存结果
result[0] = i;
result[1] = hashMap.get(temp);
}
}
return result;
}
}
```