Skip to content

Instantly share code, notes, and snippets.

@lobster1234
Last active December 14, 2015 12:48
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 lobster1234/5088590 to your computer and use it in GitHub Desktop.
Save lobster1234/5088590 to your computer and use it in GitHub Desktop.
Test if 2 numbers contained in an array add up to a given number. The time complexity is n(n-1)/2. Space complexity is constant.
public class ArraySum {
private int[] array = new int[]{1,2,3,4,5,6,7,8,9};
/**
* Do any 2 add up to this number
* @param number
* @return
*/
public boolean canAdd(int number){
for(int i=0;i<array.length;i++){
for(int j=i+1;j<array.length;j++){
System.out.println("Adding " + array[i] + " and " + array[j]);
if(array[i]+array[j]==number) {
System.out.println("The numbers " + array[i] + " and " + array[j] + " add up to " + number);
return true;
}
}
}
return false;
}
public static void main(String[] args) {
new ArraySum().canAdd(7+8);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment