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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,Return [0, 1] since nums[0] + nums[1] = 2 + 7 = 9
Approach:
- The brute force solution is to use two loops and find the two indices. The time complexity of this solution is O(n ^ 2)
- A time efficient solution would be to use hash maps and find the two numbers in O(n) time assuming hash maps take O(1) time.
Here is the ideone link for the solution: 2 Sum : http://ideone.com/O74qFR
0 comments:
Post a Comment