LeetCode #167 Two Sum II

来源:互联网 发布:java并发框架有哪些 编辑:程序博客网 时间:2024/05/21 10:32

原题:

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


技巧学习:

双指针:在排好序的数组中使用

-binary search


暴力解法:

这题同样可以用#1的方法解,但没有用到顺序这个条件。


注意:

1)if(numbers[numbers.length-1] == numbers[0])
            throw new IllegalArgumentException("No Two Sum Solution");

TestCase里给出无数个0但target不等于0的情况,所以排除了这个。但是比较机械。

2)testcase里有负数!!




Time Complexity: O(n)

Space Complexity: O(n)


双指针解法:


注意:

1)因为头尾指针make progress to the middle,所以不用担心000...0的case。

2)有人指出,两个int相加有可能超出int范围,故用long。




Time Complexity: O(n)

Space Complexity: O(1)



原创粉丝点击