leetcode167. 两数之和 II - 输入有序数组(双指针)

https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/

求数组中加起来恰好等于target的两个数的位置。

双指针问题,分别从头和尾遍历数组,如果加起来和大于target,则尾指针左移,如果加起来和小于target,则头指针右移,如果恰好则返回数组即可。

注意:1.数组的长度为****.length,没有括号!

           2.定义数组new int[]{...}

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};
            if(sum>target)
                right--;
            else
                left++;
        }
        throw new RuntimeException("在数组中没有找到这样的两个数,使得它们的和为指定值");
    }
}

猜你喜欢

转载自www.cnblogs.com/y1040511302/p/11427213.html
今日推荐