[LeetCode]167. Two Sum II - Input array is sorted

Description:

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

————————————————————————————————————————————————————————

Solution:

题意:在给定一数组中找到两个元素,其值相加等于给定数值target。

思路:我提交的第一个版本是TLE的:

[LeetCode]167. Two Sum II - Input array is sorted[LeetCode]167. Two Sum II - Input array is sorted[LeetCode]167. Two Sum II - Input array is sorted

显然,时间复杂度为O(n*n)的算法已经不符合这道题的要求,所以我应该思考如何降低时间复杂度。首先我想到导致超时的原因可能是因为n过大,而 实际上数组numbers中有许多可以不被访问的元素,如输入数组为[1,2,3,10,11,...,100],target为5,那么此时原先的办法就会循环100+次无谓的判断(只有2+3是正解),因此可以一开始初始化一个下标标记为数组大小-1,用于记录比target大的元素下标。这样在下面的双重循环里就可以以这个 标记作为循环次数,能减小不少次数,至于寻找比target大的元素下标最好可以使用二分查找等其他平均速度高的方法,这里我偷懒了只从头开始找。

[LeetCode]167. Two Sum II - Input array is sorted[LeetCode]167. Two Sum II - Input array is sorted[LeetCode]167. Two Sum II - Input array is sorted

虽然最后AC了,但觉得这始终是不太好的方法,后来在网上找更优方法,发现了可以使用哈希表记录,直接查找的方法,将时间复杂度直接变为O(n),这里就直接贴代码了,比较好理解。

[LeetCode]167. Two Sum II - Input array is sorted[LeetCode]167. Two Sum II - Input array is sorted[LeetCode]167. Two Sum II - Input array is sorted