Skip to content

Instantly share code, notes, and snippets.

@julianjupiter
Created October 20, 2022 05:42
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) {
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) {
return new int[]{x, y};
}
}
}
return null;
}
public static void main(String[] args) {
int[] numbers = {3, 9, 1, 15, 10};
int sum = 13;
var nums = twoSum(numbers, sum);
if (nums != null) {
System.out.println(nums[0] + " + " + nums[1] + " = " + (nums[0] + nums[1]));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment