Leetcode 167. Two Sum II - Input array is sorted

来源:互联网 发布:c语言调用终端命令 编辑:程序博客网 时间:2024/05/17 23:01
/** * Two-pointer approach. * pointer low starts from 0, pointer high starts from length-1 * if nums[low]+nums[high] == target return low and high * else if nums[low]+nums[high] > target means we need a samller number, move high forward * else nums[low]+nums[high] > target means we need a bigger number, move low backward */ public class Solution {    public int[] twoSum(int[] numbers, int target) {        int low = 0, high = numbers.length-1;        while (low < high) {            if (numbers[low]+numbers[high] == target) return new int[] {low+1, high+1};            else if (numbers[low]+numbers[high] < target) low++;            else high--;        }        return new int[] {};    }}

0 0
原创粉丝点击