Skip to content

Instantly share code, notes, and snippets.

@cyamba
Created April 14, 2022 14:57
Show Gist options
  • Save cyamba/7fe2c338daf372765c2c79446ff484f6 to your computer and use it in GitHub Desktop.
Save cyamba/7fe2c338daf372765c2c79446ff484f6 to your computer and use it in GitHub Desktop.
two_sum
package com.yambacode.sandbox;
import java.util.Arrays;
import java.util.stream.IntStream;
public class Main {
public static Integer[] solve_1(int target, Integer... nums) {
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new Integer[]{i, j};
}
}
}
return new Integer[]{};
}
public static Integer[] solve_2(int target, Integer... nums) {
return IntStream.range(0, nums.length - 1)
.mapToObj(i ->
IntStream.range(i + 1, nums.length)
.mapToObj(j -> ((nums[i] + nums[j]) == target) ? new Integer[]{i, j} : new Integer[]{})
.reduce((a1, a2) -> (a1.length > a2.length) ? a1 : a2).get())
.findFirst()
.get();
}
public static void main(String[] args) {
System.out.println("1.Answer is: " + Arrays.deepToString(solve_1(9, 2, 7, 11, 15)));
System.out.println("1.Answer is: " + Arrays.deepToString(solve_2(9, 2, 7, 11, 15)));
System.out.println("2.Answer is: " + Arrays.deepToString(solve_1(6, 3, 2, 4)));
System.out.println("2.Answer is: " + Arrays.deepToString(solve_2(6, 3, 2, 4)));
System.out.println("3.Answer is: " + Arrays.deepToString(solve_1(6, 3, 3)));
System.out.println("3.Answer is: " + Arrays.deepToString(solve_2(6, 3, 3)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment