LeetCode – Two Sum (Java) —题解

来源:互联网 发布:基于java的oa审批流程 编辑:程序博客网 时间:2024/06/07 09:49

题干:

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=9Output: 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/

文章有改动。

0 0
原创粉丝点击