57. 和为s的两个数字
题目描述
输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
示例1
| 输入:nums = , target = 9 输出: 或者
|
示例2
| 输入:nums = , target = 40 输出: 或者
|
解题思路
看似简单,因为是升序数组,所以一开始用暴力求解,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public int[] twoSum(int[] nums, int target) { int s = target; for(int i = 0; i < nums.length - 1; i++){ for(int j = i + 1; j < nums.length; j++){ if(nums[i] + nums[j] < s){ continue; }else if(nums[i] + nums[j] > s){ break; }else{ int[] res = new int[2]; res[0] = nums[i]; res[1] = nums[j]; return res; } } } return new int[0]; } }
|
结果超时了,转用HashMap求解。
首先当目标数组为空或只有一个值的时候,返回空。然后创建HashMap,遍历数组,将值放入HashMap,如果其中两个值相加可以得到目标值,则返回这两个值的结果。
遍历完依旧没有找到目标值,则返回空。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public int[] twoSum(int[] nums, int target) { if(nums.length < 2) return new int[0];
HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++){ int cur = target - nums[i]; if(map.containsKey(cur)){ return new int[] {cur, nums[i]}; } map.put(nums[i], i); } return new int[0]; } }
|