Started With Leetcode- Array- Q1 Two Sum
Pranjal Sailwal
Posted on May 15, 2024
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numMap = new HashMap<>();
int n = nums.length;
//Building Hash
for (int i = 0; i < n; i++) {
numMap.put(nums[i], i);
}
//Finding complement
for (int i = 0; i < n; i++) {
int complement = target - nums[i];
if (numMap.containsKey(complement) && numMap.get(complement) != i) {
return new int[]{i, numMap.get(complement)};
}
}
//for no solution
return new int[]{};
}
}
Open to updates and suggestions.
π πͺ π
π©
Pranjal Sailwal
Posted on May 15, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
career Burnout, Imposter Syndrome & More: What Junior Devs Really Experience π΅οΈββοΈ
November 28, 2024