167. Two Sum II

来源:互联网 发布:chasing cars评价 知乎 编辑:程序博客网 时间:2024/05/29 09:35

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 thesame element twice.

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

问题描述:给定一个有序数组,该数组按升序排好序。找出数组中的两个数,其和等于给定的值。返回值是这两个数的索引值index1、index2,其中index1必须小于index2。注意返回结果(index1和index2)都不为0。假设每个输入都有一个输出结果,且不能使用同一个元素两次。

分析:循环遍历该数组,先确定第一个数,然后在第一个数之后的剩余数中去找哪个数与第一个数相加等于target,相等则返回对应两个数的索引。注意这两个数的索引都不为0,而数组是从0开始的,所以需分别在对应索引+1后返回结果。

用target减去第一个数后的值,就是我们要找的目标值,由于数组是排好序的,我们可以很自然而然的想到用二分查找去快速查找该数。每次循环时,记录当前第一个数的索引(当前索引值+1),进行一次二分查找,直到找到,记录当前第二个数的索引(当前索引值+1),返回结果。

class Solution {    public int[] twoSum(int[] numbers, int target) {        int mid = 0;        int result = 0;        int[] ans = new int[2];        for(int i = 0;i < numbers.length;i++){            result = target - numbers[i];            ans[0] = i + 1;                        if(i < numbers.length - 1){                             int bottom = i + 1;                int top = numbers.length - 1;                               while(bottom <= top){                    mid = (bottom + top)/2;                    if(numbers[mid] == result){                        ans[1] = mid + 1;                        return ans;                    }                    else if(numbers[mid] < result){                        bottom = mid + 1;                    }else{                        top = mid - 1;                    }                                    }            }                   }                return ans;    }}

提交后看来答案发现了一种更简单的方法:

class Solution {    public int[] twoSum(int[] numbers, int target) {               int[] ans = new int[2];        int i = 0;        int j = numbers.length - 1;                while(i < j){            int sum = numbers[i] + numbers[j];            if(sum == target){                ans[0] = i + 1;                ans[1] = j + 1;                break;            }            else if(sum > target)                j--;            else                i++;        }        return ans;    }}