Skip to content

Instantly share code, notes, and snippets.

@tmosest
Last active January 24, 2017 21:36
Show Gist options
  • Save tmosest/dc42d6bb40a8a2e36dee7d53a212411d to your computer and use it in GitHub Desktop.
Save tmosest/dc42d6bb40a8a2e36dee7d53a212411d to your computer and use it in GitHub Desktop.
AddComplexities
//Sums from 1 to n and then from 1 to m^2
public static long example1(int n, int m)
{
long sum = 0;
//O(n)
for(int i = 1; i <= n; i++;) {
sum += i;
}
//O(m^2)
for(int i = 1; i <= m * m; i++ {
sum += i;
}
//Complexity is O(m^2 + n) = O(m^2 + n)
return sum;
}
// Determines if an array has unique elements.
public static boolean example2(int[] array)
{
boolean containsUniqueElements = true;
// Sort the elements -> O(n lg n)
Arrays.sort(array);
// Loop through and look at elements O(n)
for(int i = 0; i < array.length; i++) {
if(array[i] == array[i + i]) containsUniqueElements = false;
}
// O(n * lg n + n) = O(n * lg n)
return containsUniqueElements;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment