Created
September 6, 2017 04:28
-
-
Save courtneyfaulkner/a55f383a9d7b3c85c4f6f2579ff5e8b9 to your computer and use it in GitHub Desktop.
[CountTriplets] #practice
This file contains hidden or 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
class CountTriplets { | |
static void main(String[] args) { | |
// (-2, 0, 1) and (-2, 0, 3) == 2 | |
println "count=${count([-2, 0, 1, 3] as int[], 2)}" | |
// (1, 3, 4), (1, 3, 5), (1, 3, 7), (1, 4, 5) == 4 | |
println "count=${count([5, 1, 3, 4, 7] as int[], 12)}" | |
// (2, 3, 4), (2, 3, 5), (2, 3, 8), (2, 4, 5), (3, 4, 5) == 5 | |
println "count=${count([9, 5, 3, 2, 4, 8] as int[], 14)}" | |
} | |
static int count(int[] arr, int threshold) { | |
if (arr.length < 3) return 0 | |
Arrays.sort(arr) | |
int count = 0 | |
int i = 0, j = 1, k = 2 | |
while (i < arr.length) { | |
if (k < arr.length) { | |
int sum = arr[i] + arr[j] + arr[k] | |
if (sum < threshold) { | |
println "(${arr[i]}, ${arr[j]}, ${arr[k]})" | |
count++ | |
} | |
k++ | |
} else if (j < (arr.length - 1)) { | |
j++ | |
k = j + 1 | |
} else { | |
i++ | |
j = i + 1 | |
k = j + 1 | |
} | |
} | |
return count | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment