LeetCode – Two Sum (Java) —題解

題幹:

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/

文章有改動。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章