This is the first post discussing my solutions to LeetCode problems.Check out my LeetCode profile and follow me on Twitter.
Problem
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.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
Discussion
The basic approach to solving this problem involves the use of a data structure known as a hash table. This table stores key : value pairs. Scanning from left to right, we check each index in the array and the value stored there. We subtract this value from the target value and check if the hash table has this as a key. If it does we return an array with the indices of both values which sum to target, otherwise we add to the hash table, the values stored at the current index and the current index. Once the scanning is done,we return null as the array has no existing values.
Algorithm
HashTable map = new HashTable();
for (var i =0; i<nums.length;i++){
var curr = nums[i];//value at current index
var other = target-curr;
if (map.has(other)) return new int[] {map.get(other),i};
map.put(curr,i);
}
return null;
Solution
Java
class Solution {
public int[] twoSum(int[] nums, int target) {
Map <Integer,Integer> map = new HashMap<>();
for (int i =0; i<nums.length;i++){
int curr = nums[i];
int other = target-curr;
if (map.containsKey(other)){
return new int[] {map.get(other),i};
}
map.put(curr,i);
}
return null;
}
}
JavaScript
var twoSum = function(nums, target) {
const map= new Map();
const result=[];
for(let i=0;i<nums.length;i++){
if(map.has(target-nums[i])){
result.push(map.get(target-nums[i]));
result.push(i);
return result;
}else map.set(nums[i],i);
}
return result;
};
C#
public class Solution {
public int[] TwoSum(int[] nums, int target) {
Dictionary<int,int> map= new Dictionary<int,int>();
for(int i=0;i<nums.Length;i++){
int curr= nums[i];
int other= target-curr;
if(map.ContainsKey(other)){
int [] result= new int[2];
result[0]=map[other];
result[1]=i;
return result;
}else{
if(map.ContainsKey(curr))map[curr]=i;
else map.Add(curr,i);
}
}
return null;
}
}
If you have any questions, comment below.
Top comments (0)