Skip to content
本页目录

57-I-和为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

思路分析

基本思路: 排序好的数组,双指针分别指向最小的和最大的 判断相加的值,如果大于 target,说明右边的数大了,right指针左移 如果小于 target 说明左边的数小了,left指针右移

实现代码

csharp
public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        if(nums == null || nums.Length < 2){
            return null;
        }
        int left = 0;
        int right = nums.Length - 1;
        while(left < right){
            if(nums[left] + nums[right] < target){
                left++;
            }
            else if(nums[left] + nums[right] > target){
                right--;
            }
            else{
                return new int[]{nums[left],nums[right]};
            }
        }
        return null;
    }
}

Released under the MIT License.