Leetcode-Two Sum II - Input array is sorted

来源:互联网 发布:信息 互联网 大数据 编辑:程序博客网 时间:2024/06/05 07:08

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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

这个题目左右往中间夹逼就好了吧。Your runtime beats 40.41% of java submissions.

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





0 0
原创粉丝点击