剑指 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

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Solution 1

双指针

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left < right && nums[left] + nums[right] != target) {
            while (left < right && nums[left] + nums[right] < target)
                left++;
            while (left < right && nums[left] + nums[right] > target)
                right--;
        }
        // if (left >= right)
        // throw new RuntimeException();
        int[] result = { nums[left], nums[right] };
        return result;
    }
}

Solution 2

cpp

class Solution
{
public:
    vector<int> twoSum(vector<int> &nums, int target)
    {
        int start = 0, end = nums.size() - 1;
        vector<int> result;
        while (start < end)
        {
            if (nums[start] + nums[end] == target)
            {
                result.push_back(nums[start]);
                result.push_back(nums[end]);
                break;
            }
            while (start < end && nums[start] + nums[end] < target)
            {
                start++;
            }
            while (start < end && nums[start] + nums[end] > target)
            {
                end--;
            }
        }
        return result;
    }
};