Leetcode P0167"Two Sum II - Input array is sorted" 题解

2020/09/23 Leetcode

博文中会简要介绍Leetcode P0167题目分析及解题思路。

“Two Sum II - Input array is sorted”这道题比较基础,是p0001的简化版,这道题给定了一个排好序的数组,在这个数组里寻找和为target的两个数可以通过左右两个指针相向遍历来得到。

若当前和小于target则移动左指针,反之移动右指针,直到找到和为target的两个数。

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.

以下是Java的题解代码实现。

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

以下是C++的题解代码实现。

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

Search

    Table of Contents