当前位置:网站首页>[leetcode refers to the two numbers of offer 57. And S (simple)]

[leetcode refers to the two numbers of offer 57. And S (simple)]

2022-04-23 21:21:00 Minaldo7

subject :

Enter an ascending array and a number s, Find two numbers in an array , So that their sum is exactly s. If the sum of many pairs of numbers is equal to s, Then output any pair .

Example 1:

Input :nums = [2,7,11,15], target = 9
Output :[2,7] perhaps [7,2]
Example 2:

Input :nums = [10,26,30,31,47,60], target = 40
Output :[10,30] perhaps [30,10]

Limit :

1 <= nums.length <= 10^5
1 <= nums[i] <= 10^6

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

The problem solving process :

Double pointer

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

Execution results :

 Insert picture description here

版权声明
本文为[Minaldo7]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/111/202204210544479057.html