167. Two Sum II - Input array is sorted M

来源:互联网 发布:js 不区分大小写 编辑:程序博客网 时间:2024/06/03 12:35

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.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

public class Solution {    public int[] twoSum(int[] numbers, int target) {        int index1;        int index2;        int[] index = new int[2];        int sum;        int d_value;        int max_index2;        max_index2 = numbers.length;        for(index1=1; index1<numbers.length; ++index1){            while(numbers[index1-1]+numbers[numbers.length-1]<target){                ++index1;            }            for(index2=index1+1; index2<=max_index2; ++index2){                sum = numbers[index1-1]+numbers[index2-1];                d_value = target - sum;                if(d_value == 0){                    index[0] = index1;                    index[1] = index2;                    return index;                }                if(d_value < 0){                    max_index2 = index2-1;                    break;                }            }        }        return index;    }}

假设数组a = [a1,a2,a3,a4,a5,a6...,an]

1.当前从index1开始遍历a[index1]+a[index2],如果a[index1]+an,即a[index1]与a中最大数的和还是比target小,那么就不必从index1开始遍历求和了而将index1+1,对应代码:

while(numbers[index1-1]+numbers[numbers.length-1]<target)

2.假设a[index1]+a[index2-1]<target,而a[index1]+a[index2]>target,则a[index1+1]+a[index2]>traget一定成立,那么:如果双重循环外层循环到index1+1,那么内层循环只需要从a[index1+2]循环到a[index2-1],对应代码:

 if(d_value < 0){<span style="white-space:pre"></span>max_index2 = index2-1;        break; }

虽然accept了,但是感觉还可以优化时间复杂度。

比如已经遍历了a[index1]+a[index1+1],a[index1]+a[index1+2]...,a[index1]+a[n],

那么在遍历a[index1+1]+a[index1+2],a[index1+1]+a[index1+3]...,a[index1+1]+a[n]时候可由a[index1+1]-a[index1]的值,加上上次遍历的得到的信息进一步缩小这次的遍历范围,至于怎么做没想清楚,又感觉不行。



后来又优化了下:

while(numbers[index1-1]+numbers[numbers.length-1]<target){                ++index1;            }

改成了

while(numbers[index1-1]+numbers[max_index2-1]<target){                ++index1;            }

0 0