DSA_sheets/dsa/src/main/java/com/hithomelabs/dsa/array/two_sum/HashMapSolution.java

27 lines
975 B
Java

package com.hithomelabs.dsa.array.two_sum;
import java.util.Map;
public class HashMapSolution implements Solvable {
@Override
public int[] solve(int[] nums, int target) {
// Create a map to store the numbers and their corresponding indices
Map<Integer, Integer> map = new HashMap();
// Iterate through the array of numbers
for (int i = 0; i < nums.length; i++){
// Check if the complement (target - current number) exists in the map
if (map.containsKey(target - nums[i])){
// If found, return the indices of the current number and its complement
int[] solution = {i, map.get(target - nums[i])};
return solution;
}
else
// If not found, add the current number and its index to the map
map.put(nums[i], i);
}
// Return null if no solution is found
return null;
}
}