//给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
//
// 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
//
//
//
// 示例:
//
// 给定 nums = [2, 7, 11, 15], target = 9
//
//因为 nums[0] + nums[1] = 2 + 7 = 9
//所以返回 [0, 1]
//
// Related Topics 数组 哈希表
// 👍 8825 👎 0
//两数之和
package editor.cn;
import java.util.HashMap;
import java.util.Map;
class 两数之和 {
public static void main(String[] args) {
Solution solution = new 两数之和().new Solution();
int[] nums = new int[]{2, 7, 11, 15};
int target = 9;
//暴力破解法
solution.twoSum(nums, target);
//两次哈希法
TwiceHash twiceHash = new 两数之和().new TwiceHash();
twiceHash.twoSum(nums, target);
OnceHash onceHash = new 两数之和().new OnceHash();
onceHash.twoSum(nums, target);
}
//原方法名也不能修改改了插件提交不上去 暴力法
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
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 (target == nums[i] + nums[j]) {
System.out.println("[ " + i + ", " + j + " ]");
return new int[]{i, j};
}
}
}
throw new RuntimeException("没有找到");
}
}
//leetcode submit region end(Prohibit modification and deletion)
/**
* @Description 方法二 两遍哈希表 数组都先放进去 从前面往后找
* @Author WangWenpeng
* @Date 15:52 2020/8/6
* @Param
*/
class TwiceHash {
public int[] twoSum(int[] nums, int target) {
//第一遍放进map中去,值作为key,index作为value
Map<Integer, Integer> map = new HashMap<>();
int difference = 0;
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
//第二遍开始寻找,map中有没有差值的key,查到key的value就是数组的index
for (int i = 0; i < nums.length; i++) {
difference = target - nums[i];
if (map.containsKey(difference) && map.get(difference) != i) {
System.out.println("[ " + i + ", " + map.get(difference) + " ]");
return new int[]{i, map.get(difference)};
}
}
throw new RuntimeException("没有找到");
}
}
/**
* @Description 方法三 一遍哈希表 从后面往前找
* @Author WangWenpeng
* @Date 16:09 2020/8/6
* @Param
*/
class OnceHash {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
int difference = 0;
for (int i = 0; i < nums.length; i++) {
//往map中先放进去
map.put(nums[i], i);
// 看差值是否在map中存在
difference = target - nums[i];
if (map.containsKey(difference) && map.get(difference) != i) {
System.out.println("[ " + map.get(difference) + ", " + i + " ]");
return new int[]{map.get(difference), i};
}
}
throw new RuntimeException("没有找到");
}
}
}
个人网站
http://www.51pro.top
公众号