leetcode (2) 两数之和改进
其实这个问题逻辑还是挺简单的, 就是 num[j] + num[i] = target; 输出{i,j}
不知道有没有人用两遍 map去处理的呢
//给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
//
// 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
//
//
//
// 示例:
//
// 给定 nums = [2, 7, 11, 15], target = 9
//
//因为 nums[0] + nums[1] = 2 + 7 = 9
//所以返回 [0, 1]
//
// Related Topics 数组 哈希表
// 👍 8759 👎 0
package com.cute.leetcode.editor.cn;
public class TwoSum {
public static void main(String[] args) {
Solution solution = new TwoSum().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<int, int> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complt = target - nums[i];//补数
if (map.containsKey(complt) && map.get(complt) != i) {
return new int[] { i, map.get(complt) };
}
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
第一遍遍历将所有的下标和值建立联系生成一个map,然后再遍历map,complement = target - nums[i] 大家都应该知道上面分析过了那个等式( num[j] + num[i] = target)的变形,发现彩蛋了嘛
真正的找的工作就是complement = target - nums[i] 使用逆向使用等式,加上map的containsKey(complement);循环一遍。
想想初始化可不可以去掉,或者是换一下。
//给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 // // 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 // // // // 示例: // // 给定 nums = [2, 7, 11, 15], target = 9 // //因为 nums[0] + nums[1] = 2 + 7 = 9 //所以返回 [0, 1] // // Related Topics 数组 哈希表 // 👍 8759 👎 0 package com.cute.leetcode.editor.cn; public class TwoSum { public static void main(String[] args) { Solution solution = new TwoSum().new Solution(); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complt = target - nums[i]; if (map.containsKey(complt)) { return new int[] { map.get(complt), i }; } map.put(nums[i], i); } } } //leetcode submit region end(Prohibit modification and deletion) }
你想到了嘛
加油!
愿你我,长安,长乐,不悲,不怂,
和生活一刚到底,游刃有余,笑傲此生。

浙公网安备 33010602011771号