LeetCode 167 Two Sum II - Input array is sorted (两点法)

来源:互联网 发布:万象域名 编辑:程序博客网 时间:2024/06/07 05:44

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. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2


题目链接:https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/


题目分析:因为数组有序,因此可以使用两点法,一指针在开头,一指针在结尾,若相加小于target,则开头指针后移,大于则结尾指针前移,相等就break

public class Solution {    public int[] twoSum(int[] numbers, int target) {        int[] ans = new int[2];        int sz = numbers.length;        int l = 0, r = sz - 1;        while (l < r) {            if (numbers[l] + numbers[r] < target) {                l ++;            }            else if (numbers[l] + numbers[r] > target) {                r --;            }            else {                ans[0] = l + 1;                ans[1] = r + 1;                break;            }        }        return ans;    }}


0 0
原创粉丝点击