Leetcode: Find two value with Sum
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,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Solution
solution 1: The brute force
The brute force approach is simple. Loop through each element x and find if there is another value that equals to target-x.
solution 2: Improved brute force
The idea is simple too: sort the vector than perform binary search to find target-x
solution 3: Hash table
Using hash table to find x and anther target-x
Check out the Two sum.
近期评论