I am supposed to create a O(n log(n))
algorithm that checks if sum of 2 numbers in a int[] == given number.
eg. Given [1,4,7,2,3,4] there will be a sum
Similar to @user384706, however you can do this with in O(n)
.
What they say is the following: S=[1,4,7,2,3,4]
Add these to a HashSet, ideally TIntHashSet (but the time complexity is the same)
int total = 9;
Integer[] S = {1, 4, 7, 2, 3, 4, 6};
Set set = new HashSet(Arrays.asList(S));
for (int i : set)
if (set.contains(total - i))
System.out.println(i + " + " + (total - i) + " = " + total);
prints
2 + 7 = 9
3 + 6 = 9
6 + 3 = 9
7 + 2 = 9