Last active
December 14, 2015 12:48
-
-
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.
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
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