🎀 The Problem
Given an array of integers nums and an integer target, return the 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.
Example:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
👩💻 My Answer
class Solution {
public int[] twoSum(int[] nums, int target) {
int index = 0;
while(index < nums.length){
for (int i = index+1; i < nums.length; i++) {
if (nums[i] == target - nums[index]) {
int[] output = new int[2];
output[0] = index;
output[1] = i;
return output;
}
}
index++;
}
return null;
}
}
Pro & Con
- ✖️ Runtime & Memory
- ✖️ Brute Force Code (nested loop)
💋 Ideal Answer
Approach - "Hash Table"
I read the solution on LeetCode and found that using a hash table is the fastest one for this.
New Code
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap();
for (int i = 0; i < nums.length; i++) {
if (!map.containsKey(target - nums[i]))
map.put(nums[i], i);
else
return new int[] {map.get(target - nums[i]),i};
}
return null;
}
}
💡 What I Learned
- How I construct int[] in return line
return new int[] {map.get(target - nums[i]),i};
Top comments (0)