Created
August 28, 2017 02:56
-
-
Save thmain/b5649e1c5b601fc510d9cfa854551928 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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