This is my second posting for solving one of the LeetCode programming problem called Two Sum.
The problem is simple: “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].
Idea
- We need to have a data structure that contains
{Number -> index}
- If there exists such two numbers where
num1 + num2 = target
, then we would also havenum2 = target — num1
Pseudocode
class Solution {
public int[] twoSum(int[] nums, int target) {
// 1. initialize HashMap for {Number -> Index} // 2. iterate the array // 3. check if such 'num2' exists in the hashmap
// 4. if not exist, add new pair to the hashmap
}
}
Code
Note that you can return the result as return new int[]{i, map.get(nums2)
Very straightforward question using HashMap. Thanks for reading!