Question
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly* one solution, and you may not use the same* element twice.
You can return the answer in any order.
Algorithm
A brute force way is travail. O(n^n) time complexity.
We need to come up a better solution for this world class famous question. Actually for a problem that you have never seen, try to find pattern for some problem you solved. If not, try to find some information you can utilize.
For this problem, the information is that you can store the value you seen in somewhere. And next time you find its complementary to the target by looking for if the target-num is in the seen values.
Code
class Solution { public int[] twoSum(int[] nums, int target) { int[] res = new int[2]; Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(target - nums[i])) { res[0] = i; res[1] = map.get(target - nums[i]); } else { map.put(nums[i], i); } } return res; } }