Created
June 14, 2015 18:26
-
-
Save rcgonzalezf/de4359cbc8a4cbab597a to your computer and use it in GitHub Desktop.
Code for solution of Udemy course.
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; | |
import java.util.Set; | |
/** | |
* https://www.udemy.com/programming-code-interview/#/lecture/2519488 | |
*/ | |
public class TargetSumArray { | |
public static void main(String[] args) { | |
TargetSumArray tsa = new TargetSumArray(); | |
int[] testArray = new int[]{9,5,2,7}; | |
int targetSum = 7; | |
System.out.println("true is: "+ tsa.hasPairThatSumsTo(testArray, targetSum)); | |
targetSum = 11; | |
System.out.println("true is: "+ tsa.hasPairThatSumsTo(testArray, targetSum)); | |
targetSum = 3; | |
System.out.println("false is: "+ tsa.hasPairThatSumsTo(testArray, targetSum)); | |
testArray = new int[]{}; | |
System.out.println("false is: "+ tsa.hasPairThatSumsTo(testArray, targetSum)); | |
testArray = new int[]{1}; | |
System.out.println("false is: "+ tsa.hasPairThatSumsTo(testArray, targetSum)); | |
} | |
public boolean hasPairThatSumsTo(int[] numbers, int targetSum ) { | |
Set<Integer> lookupTable = new HashSet<>(); | |
for(int number: numbers) { | |
int substraction = targetSum - number; | |
if(lookupTable.isEmpty()) { | |
lookupTable.add(substraction); | |
} else { | |
if (lookupTable.contains(number)) { | |
return true; | |
} else { | |
lookupTable.add(substraction); | |
} | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment