其他分享
首页 > 其他分享> > 剑指 Offer 57. 和为s的两个数字

剑指 Offer 57. 和为s的两个数字

作者:互联网

题意

在一个有序数组里找两个和为s的数字

思路

代码(二分查找)

class Solution {
public:
    int find_pair(vector<int>& nums, int target) {
        int left = 0, right = nums.size() - 1;
        while(left <= right) {
            int mid = left + (right - left) / 2;
            if(nums[mid] == target) {
                return mid;
            }else if(nums[mid] > target) {
                right = mid - 1;
            }else {
                left = mid + 1;
            }
        }
        return -1;
    }
    vector<int> twoSum(vector<int>& nums, int target) {
        for(auto n: nums) {
            int p = find_pair(nums, target - n);
            if(p != -1) {
                return {n, nums[p]};
            }
        }
        return {};
    }
};

代码(双指针法)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int cur1 = 0, cur2 = nums.size() - 1;
        while(cur1 != cur2) {
            int sum = nums[cur1] + nums[cur2];
            if(sum == target) {
                return {nums[cur1], nums[cur2]};
            }else if(sum > target) {
                cur2--;
            }else {
                cur1++;
            }
        }
        return {};
    }
};

标签:return,target,nums,int,57,Offer,cur1,sum,数字
来源: https://www.cnblogs.com/MartinLwx/p/14398053.html