Leetcode刷题笔记——167Two Sum II - Input array is sorted

一、Problem

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

二、Solution

给定一个以升序排序的数组,找到两个数使其相加等于目标数,并返回这两个数的索引,索引是从1开始的。

思路1:设置两个索引 i 和 j 分别指向数组的首和尾位置。则numbers[i]+numbers[j]有三种情况

1)numbers[i]+numbers[j]==target

2)numbers[i]+numbers[j]>target  :则索引j 向前移一位(因为数组是升序的,向前移后 j 指向的元素值变小)

3)  numbers[i]+numbers[j]<target : 则索引 i 向后移一位 (因为数组是升序的,向后移 i 指向的元素值变大)

c++代码

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int l = 0,r = numbers.size() - 1;  // 设置两个索引l和r分别指向数组首尾
        while (l < r){   
            if (numbers[l] + numbers[r] == target) {
                int res[2] = { l + 1,r + 1 };  //  因为l的初始值为0,题中要求索引从1开始,所以加1
                return vector<int>(res, res + 2);  
            }
            else if (numbers[l] + numbers[r] < target)
                l++;
            else
                r--;

         }
    }
};

猜你喜欢

转载自www.cnblogs.com/guo7533/p/10422215.html