您的位置:首页 > 其它

LeetCode-167:Two Sum II - Input array is sorted (固定和的元素的索引 II)

2017-10-24 20:59 531 查看

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=9
Output: 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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode 算法 Array