class Solution {
public int[] twoSum(int[] nums, int target) {
// Map<Integer, Integer> map = new HashMap<>();
// for (int i = 0; i < nums.length; i++) {
// int res = target - nums[i];
// if (map.containsKey(res)) {
// return new int[]{res, nums[i]};
// }
// map.put(nums[i], res);
// }
// return new int[]{};
int i = 0, j = nums.length - 1;
while (i < j) {
if (nums[i] + nums[j] < target) {
i++;
} else if (nums[i] + nums[j] > target) {
j--;
} else {
return new int[]{nums[i], nums[j]};
}
}
return new int[]{};
}
}
剑指 Offer 57. 和为s的两个数字
最新推荐文章于 2021-12-01 17:19:18 发布