This one is very favourite question of java interviewers, In which you have to find the two numbers in an array that add up to a specific target sum, you can use the Two Sum problem solution. Here's an example implementation in Java:
javaimport java.util.HashMap;
import java.util.Map;
public class TwoSum {
public static int[] findTwoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
return new int[]{-1, -1}; // If no solution is found
}
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
int[] result = findTwoSum(nums, target);
if (result[0] != -1 && result[1] != -1) {
System.out.println("Two numbers found: " + nums[result[0]] + " and " + nums[result[1]]);
} else {
System.out.println("No two numbers found that add up to the target sum.");
}
}
}
In this example, the findTwoSum
method takes an array of integers (nums
) and a target sum as parameters. It uses a HashMap
to store the complement of each element (the difference between the target and the current number) and its corresponding index. It iterates through the array, checking if the complement exists in the HashMap
. If found, it returns the indices of the two numbers that add up to the target sum. If no solution is found, it returns [-1, -1]
.