leetcode 167 Two Sum II - Input array is sorted

本文介绍了一种高效求解有序数组中两数之和问题的方法。通过双指针技巧,实现了O(n)的时间复杂度,避免了传统两层循环的低效方式。

题目详情

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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
题目的输入是一个已经按照升序排列的整数数组和一个目标数字。
要求的输出是:数组中加和恰好为目标数字的两个元素的位置(这里的位置不从0开始计算)。
同时题目假设每组输入恰好只有一个答案,并且不能重复使用同一元素。

理解

这道题是可以用两层循环蛮力解决的,但是效率太低了。我们如何能得到一个复杂度为n的解法呢?
我们可以声明两个指针left,right分别指向数组中最小的元素、最大的元素。
如果这两个元素和大于目标数组,right指针左移;如果小于,left指针右移。如果等于,则返回这两个元素的位置(记得用数组的index数值加一)

解法

    public int[] twoSum(int[] numbers, int target) {

        int[] res = new int[2];
        if(numbers == null || numbers.length <2){
            return res;
        }
        
        int left = 0;
        int right = numbers.length-1;        
        while(left < right){
            int temp = numbers[left] + numbers[right];
            if(temp == target){
                res[0] = left + 1;
                res[1] = right +1;
                return res;
            }else if(temp >target){
                right --;
            }else{
                left++;
            }
        }
        
        
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值