leetcode 167 Two Sum II - Input array is sorted

题目详情

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;
    }
相关文章
相关标签/搜索