Problem
Here.
Summary
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
The return format had been changed to zero-based indices.
Analyse
Be careful
- zero-based indices.
- [1, 3, 4, 2]. 4 + 2 = 6 is ok. But not for 3 + 3 = 6.
- [1, 3, 3, 2]. 3 + 3 = 6 is ok.
Brute force
Loop through each element x and find if there is another value equals to target - x.
|
|
Complexity: O(n^2).
Binary Search
One way to improve the brute force is sort the whole array and loop through each element x and find if there is another value equals to target - x by binary search.
Complexity: O(nlogn).
Hash Map
While we iterate and inserting elements into the hash table, we also look back to check if current element’s complement already exists in the table. If it exists, we have found a solution and return immediately.
16 / 16 test cases passed.
Status: Accepted
Runtime: 26 ms
|
|
Complexity: O(n).
近期评论