Java简单算法求两数之和
程序员文章站
2022-07-10 18:29:52
题目给定 nums = [2, 7, 11, 15], target = 9因为 nums[0] + nums[1] = 2 + 7 = 9所以返回 [0, 1](1)方法一:双重for循环,简单粗暴class Solution { public int[] twoSum(int[] nums, int target) { int[] index = new int[2]; //双重递归 for(int i = 0;i < nums....
题目
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
(1)方法一:双重for循环,简单粗暴
class Solution { public int[] twoSum(int[] nums, int target) { int[] index = new int[2]; //双重递归 for(int i = 0;i < nums.length ;i++){ for(int j = nums.length-1;j>i;j--){ if(nums[i] + nums[j] == target){ index[0] = i; index[1] = j; return index; } } } return index; } }
结果(1)
方法二:用map,先减去一个值,判断剩下的值是否在map中,不在的添加key-value
class Solution { public int[] twoSum(int[] nums, int target) { int[] index = new int[2]; Map<Integer,Integer> map = new HashMap<>(); for(int i = 0;i < nums.length ;i++){ int other_num = target - nums[i]; if(null != map.get(other_num)){ index[0] = map.get(other_num); index[1] = i; return index; } map.put(nums[i],i); } return index; } }
结果(2)
本文地址:https://blog.csdn.net/qq_37712731/article/details/107898809