1 Sum of Two
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.
Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Method 1:
Brute-Force (also known as generate-and-test/Conquer-and-divide): It's typically used in the problem that: 1)Problem size is limited; 2)can easily reduce the set of solution candidate.
for each item1 in array:
{
for each item2 in array:
if (item1 + item2 = target):
return index[item1] and index[item2]
}
In this problem, we can use two for loop to traverse through all the elements in the array. But the complexity will be O(n^2)
Method 2:
Hashmap: