leetcode算法题-数组-两数之和II-输入有序数组

题目描述

给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

package com.zcl.数组;

/**
 * Author:markusZhang
 * VM Args:
 * Date:Create in 2020/2/1 14:55
 */
public class 两数之和II输入有序数组 {
    /*
    如果是关于数组相关的题目,并且规定数组是有序的,那你就该偷偷窃喜了,它远比动态规划简单多了
    可以先用双指针算法来思考这个问题(并不绝对哈!我不负责任的,嘻嘻)
    该算法时间复杂度O(n) 因为数组的每个元素只遍历了一遍
    空间复杂度O(1),因为只是用了两个指针
     */
    public int[] twoSum(int[] numbers, int target) {
        int indexL = 0;
        int indexR = numbers.length-1;
        while(indexL<indexR){
            int sum = numbers[indexL]+numbers[indexR];
            if(sum<target){
                indexL++;
            }else if(sum>target){
                indexR--;
            }else{
                return new int[]{indexL+1,indexR+1};
            }
        }
        throw new IllegalArgumentException("没有");
    }
}

猜你喜欢

转载自blog.csdn.net/MarkusZhang/article/details/104134022