Skip to content

Instantly share code, notes, and snippets.

@julianjupiter
Last active September 17, 2024 14:35
Show Gist options
  • Save julianjupiter/3b8363f9b01a721bc5932d8e40e40bf0 to your computer and use it in GitHub Desktop.
Save julianjupiter/3b8363f9b01a721bc5932d8e40e40bf0 to your computer and use it in GitHub Desktop.
Given an array of distinct integers and a target sum, find two numbers in the array that add up to the target sum.
public class TwoSum {
public static int[] twoSum(int[] a, int sum) {
var result = new int[2];
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
int x = a[i];
int y = a[j];
if ((x + y) == sum) {
result[0] = x;
result[1] = y;
}
}
}
return result;
}
public static void main(String[] args) {
int[] numbers = {3, 9, 1, 15, 10};
var sum = 10;
var result = twoSum(numbers, sum);
System.out.println(result[0] + " + " + result[1] + " = " + (result[0] + result[1]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment