Skip to content

Instantly share code, notes, and snippets.

@m3hdiii
Created January 3, 2021 08:33
Show Gist options
  • Save m3hdiii/dfd90928f597e25bf0be4b60dffdeffd to your computer and use it in GitHub Desktop.
Save m3hdiii/dfd90928f597e25bf0be4b60dffdeffd to your computer and use it in GitHub Desktop.
Write Java code for this problem and analyze its complexity: Given an array of distinct integers and a target sum, find two numbers in the array that add up to the target sum.
import java.util.LinkedHashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) {
int[] arr = {4, 5, 7, -5 - 3, 2, 8, 5, -1, 3, 8};
int[] distinctIntArray = makeDistinct(arr);
getPairsCount(distinctIntArray, 9);
}
public static void getPairsCount(int[] arr, int targetSum) {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if ((arr[i] + arr[j]) == targetSum) {
System.out.println(String.format("Sum of [%d] and [%d] yield [%d] which is the target sum!", arr[i], arr[j], targetSum));
}
}
}
}
public static int[] makeDistinct(int[] ints){
Set<Integer> setString = new LinkedHashSet<>();
for(int i=0;i<ints.length;i++){
setString.add(ints[i]);
}
int[] distinctArray = setString.stream().mapToInt(Number::intValue).toArray();
return distinctArray;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment