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

Tag: 剑指-Offer Posted on 2022-02-27 17:53:55 Edited on 2022-02-27 17:54:36 Views: 162

概述

https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof/

两数之和,但是这里是排序后的数组。

前后指针

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

未经允许,禁止转载,本文源站链接:https://iamazing.cn/