输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
示例 1:
输入:nums = [2,7,11,15], target = 9 输出:[2,7] 或者 [7,2]
示例 2:
输入:nums = [10,26,30,31,47,60], target = 40 输出:[10,30] 或者 [30,10]
限制:
1 <= nums.length <= 10^51 <= nums[i] <= 10^6- class Solution {
- public int[] twoSum(int[] nums, int target) {
- Set
hashSet = new HashSet<>(); -
- for (int num : nums) {
- if (hashSet.contains(target - num)) {
- return new int[]{target - num, num};
- }
-
- hashSet.add(num);
- }
-
- return new int[2];
- }
- }
经典两数之和题,边遍历数组边把元素放入哈希表中,对每个元素都寻找 s 和它的差是否在哈希表中,如果存在则代表这两个数之和为 s 。
PS.虽然但是,代码里的方法参数是 target 不是 s 诶……