Skip to content

Instantly share code, notes, and snippets.

@lobster1234
Created March 9, 2013 03:56
Show Gist options
  • Save lobster1234/5122448 to your computer and use it in GitHub Desktop.
Save lobster1234/5122448 to your computer and use it in GitHub Desktop.
Check if a collection contains 2 numbers that add up to the input. This uses a hashmap so that the computational complexity is constant.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class ArraySumWithMap {
private Map<Integer, Integer> numbers = new HashMap<Integer, Integer>();
/**
* Do any 2 add up to this number
* @param number
* @return
*/
public boolean canAdd(int number){
boolean canAdd = false;
Iterator<Integer> it = numbers.keySet().iterator();
while(it.hasNext()){
int numberToFind = number - it.next();
if(numbers.containsKey(numberToFind)){
canAdd = true;
break;
}
}
return canAdd;
}
public ArraySumWithMap add(int n){
numbers.put(n,n);
return this;
}
public static void main(String[] args) {
ArraySumWithMap problem = new ArraySumWithMap();
problem.add(1).add(2).add(3).add(4).add(5);
System.out.println(problem.canAdd(0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment