LeetCode -两数之和
LeetCode 第一题:
废话不多说,首先放上LeetCode的地址.
https://leetcode.com/problems/two-sum/ 英文版
https://leetcode-cn.com/problems/two-sum/ 中文版
接下来我们来分析一下这个题目,题目描述:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
我们从题目上可以得知以下的信息,首先数字不可以重复使用,什么算是重复使用呢?重复使用指的是不可以使用 num[0]+nums[0],这样进行计算,但是如果nums[1] == nums[0],这个是可以使用的,两个数字只是相等而已。那么接下来,还有一个问题是这个数组是无序的。
这样的话,我们可以把出现过的数字放入到hashMap中key是数字,value是下标。有了这个map,以后我们再去遍历数组。如果target - nums[i] 在map的key里面,就说明找到了我们需要的结果就是两个下标,一个是i,另外一个是 map.get(target-nums[i]),但是这里有一个注意点,。 i != map.get(target-nums[i]),也就是题目中提到的不能重复使用。
然后是代码:
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
//记录数字和下标的对应
HashMap<Integer, Integer> maxIndexMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
maxIndexMap.put(nums[i], i);
}
//遍历数组
for (int i = 0; i < nums.length; i++) {
if (maxIndexMap.keySet().contains(target - nums[i]) && i != maxIndexMap.get(target - nums[i])) {
//坐标小的方前面
result[0] = i < maxIndexMap.get(target - nums[i]) ? i : maxIndexMap.get(target - nums[i]);
//坐标大的放后面
result[1] = i > maxIndexMap.get(target - nums[i]) ? i : maxIndexMap.get(target - nums[i]);
}
}
return result;
}