LeetCode-167:Two Sum II

来源:互联网 发布:最好的源码下载网站 编辑:程序博客网 时间:2024/05/22 17:04

Question

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.

Example

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

问题解析:

给定升序排序数组,找到两个和为给定数字的元素,返回二者位置。注意index1 < index2,且不使用重复元素。

Answer

Solution 1:

左右两指针相加靠近。

  • 注意题目与LeetCode-1:Two Sum存在不同的地方,本题要求index1 < index2,可以使用除与LeetCode-1相同的HashMap之外其他的方法。
  • 题中要求index1 < index2,那么我们可以利用这样的性质,设置左右两个指针,从两端向中间逼近,每次都用两个数判断是否等于目标值,等于则返回,不等则判断大小,增减左右指针。
class Solution {    public int[] twoSum(int[] numbers, int target) {        int left = 0;        int right = numbers.length-1;        while (numbers[left] + numbers[right] != target){            if (numbers[left] + numbers[right] > target){                right--;            }else{                left++;            }        }        return new int[]{left+1, right+1};    }}
  • 时间复杂度:O(n);空间复杂度:O(1)
原创粉丝点击