Skip to content

Instantly share code, notes, and snippets.

@thmain
Created August 28, 2017 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/b5649e1c5b601fc510d9cfa854551928 to your computer and use it in GitHub Desktop.
Save thmain/b5649e1c5b601fc510d9cfa854551928 to your computer and use it in GitHub Desktop.
import java.util.HashSet;
public class ThreeNumbersSumZeroHashing {
//we need to find a + b + c = 0
//OR reduce the problem c = -(a+b)
public static void find(int [] x){
for (int i = 0; i <x.length ; i++) {
int a = x[i];
HashSet<Integer> set = new HashSet<Integer>();
for (int j=i+1; j<x.length; j++) {
int b = x[j];
int c = -(a+b);
if(set.contains(c)){
System.out.println("Found 3 elements whose sum is = 0");
System.out.println("Elements are " + a + " " + b + " " + c);
return;
}else
set.add(b);
}
}
}
public static void main(String[] args) {
int a [] = { 3,-1,-7,-4,-5,9,10};
find(a);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment