【LeetCode】167. Two Sum II

来源:互联网 发布:杭州程序员招聘网站 编辑:程序博客网 时间:2024/06/07 06:56

问题描述

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

解决方法

方法1

begin初始值指向0,end初始值指向length-1,将数组中的两个索引值相加,结果如果大于target,则将end–,如果小于target,则将begin++,直至找到对应索引值等于target值。

class Solution {    public int[] twoSum(int[] numbers, int target) {        int[] indices = new int[2];        if(numbers == null || numbers.length < 2) return indices;        int begin = 0;        int end = numbers.length - 1;        while(begin < end) {            int sum = numbers[begin] + numbers[end];            if(sum == target)            {                indices[0] = begin + 1;                indices[1] = end + 1;                break;            }            else if(sum < target)                begin++;            else                end--;        }        return indices;    }}

方法2

fix the first element A[0] and do binary search on the remaining n-1 elements. If cannot find any element which equals target-A[0], Try A[1]. That is, fix A[1] and do binary search on A[2]~A[n-1]. Continue this process until we have the last two elements A[n-2] and A[n-1].

This gives a time complexity lg(n-1) + lg(n-2) + … + lg(1) ~ O(lg(n!)) ~ O(nlgn). So it is less efficient than the O(n) solution.
每次固定一个元素x(0~length-1),然后target-x得到一个值gap,需要做的就是找到在剩余的数值中哪个索引值等于gap,寻找过程为二分查找法,复杂度近似为O(nlgn)。

class Solution{    public int[] twoSum(int[] numbers, int target)    {        int[] indices = new int[2];        if(numbers == null || numbers.length < 2) return indices;        for(int i=0; i<numbers.length-1; i++)        {            int begin = i + 1, end = numbers.length - 1;            int gap = target - numbers[i];            while(begin <= end)            {                int middle = begin + (end - begin) / 2;                if(numbers[middle] == gap)                {                    indices[0] = i + 1;                    indices[1] = middle + 1;                    break;                }                else if(numbers[middle] < gap)                    end = middle - 1;                else                    begin = middle + 1;            }        }        return indices;    }}
原创粉丝点击