Q1. Given an array of integers, find two numbers such that they add up to a specific target number? For example, Given numbers: {2, 3, 8, 7, 5} Target number: 9 Result: 2 and 7 A1. Solution 1: Store processed numbers in a set.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.management.RuntimeErrorException; public class Sum2NumsToATargetNumberTest { public static int[] findNumsThatSumToTargetNum(int[] numbers, int target) { Set<Integer> processedNumbers = new HashSet<>(); boolean foundSum = false; int[] result = new int[2]; for (int i = 0; i < numbers.length; i++) { int reqNumber = target  numbers[i]; System.out.println("current number=" + numbers[i] + " , requiredNumber = " + reqNumber); if(processedNumbers.contains(reqNumber)){ result[0] = numbers[i]; result[1] = reqNumber; foundSum = true; break; } else { processedNumbers.add(numbers[i]); } } if(!foundSum){ throw new RuntimeException("Sum is not found !!"); } return result; } } 
Solution 2: Sort the numbers…...
Members Only Content
This content is for the members with any one of the following paid subscriptions:
30DayJavaJEECareerCompanion, 90DayJavaJEECareerCompanion, 180DayJavaJEECareerCompanion, 365DayJavaJEECareerCompanion and 2YearJavaJEECareerCompanion
Log In 
Register 
Try free FAQs 
Home