本问题对应的 leetcode 原文链接:剑指 Offer 57. 和为s的两个数字
问题描述
输入一个递增排序的数组和一个数字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^5
1 <= nums[i] <= 10^6
解题思路
视频讲解直达: 本题视频讲解
代码实现
class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums == null || nums.length < 2){
return new int[0];
}
int i = 0, j = nums.length - 1;
while(i < j){
if(nums[i] + nums[j] > target){
j--;
}else if(nums[i] + nums[j] < target){
i++;
}else{
return new int[]{nums[i], nums[j]};
}
}
return new int[0];
}
}
Python
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if nums is None or len(nums) < 2:
return []
i, j = 0, len(nums) - 1
while i < j:
if nums[i] + nums[j] > target:
j -= 1
elif nums[i] + nums[j] < target:
i += 1
else:
return [nums[i], nums[j]]
return []
C++
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
if (nums.empty() || nums.size() < 2) {
return {};
}
int i = 0, j = nums.size() - 1;
while (i < j) {
if (nums[i] + nums[j] > target) {
j--;
} else if (nums[i] + nums[j] < target) {
i++;
} else {
return {nums[i], nums[j]};
}
}
return {};
}
};
Go
func twoSum(nums []int, target int) []int {
if nums == nil || len(nums) < 2 {
return []int{}
}
i, j := 0, len(nums) - 1
for i < j {
if nums[i] + nums[j] > target {
j--
} else if nums[i] + nums[j] < target {
i++
} else {
return []int{nums[i], nums[j]}
}
}
return []int{}
}
JS
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
if (nums == null || nums.length < 2) {
return [];
}
let i = 0,
j = nums.length - 1;
while (i < j) {
if (nums[i] + nums[j] > target) {
j--;
} else if (nums[i] + nums[j] < target) {
i++;
} else {
return [nums[i], nums[j]];
}
}
return [];
};