您的位置:首页 > 编程语言 > Java开发

LeetCode – Two Sum (Java) —题解

2016-03-19 20:31 489 查看
题干:

Given an array of integers, 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.

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


My First Try

This problem is pretty straightforward. We can simply examine every possible pair of numbers in this integer array.

Time complexity in worst case: O(n^2).



如我后来注释的那样,该方法并不能减小时间复杂度,可能只是筛选出了很小的一部分数据。在两个for循环中消耗了许多时间。

Better Solution

Use HashMap to store the target value.



Time complexity depends on the put and get operations of HashMap which is normally O(1).

Time complexity of this solution is O(n).

转载自:http://www.programcreek.com/2012/12/leetcode-solution-of-two-sum-in-java/

文章有改动。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: