Created
November 17, 2017 23:25
-
-
Save shailrshah/684ce2a655c0dac1af7be46cf6a83d08 to your computer and use it in GitHub Desktop.
Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
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
// if a > b and a > c, then a < b + c for a triangle to be formed | |
public int triangleNumber(int[] a) { | |
int n = a.length; | |
if(n < 3) return 0; | |
int count = 0; | |
Arrays.sort(a); | |
for(int i = 2; i < n; i++) { | |
int left = 0, right = i-1; | |
while(left < right) { | |
if(a[left] + a[right] > a[i]){ | |
// (left, right, i), (left+1, right, i) .. (right-1, right, i) are all valid | |
count += right-left; | |
right--; | |
} | |
else | |
left++; | |
} | |
} | |
return count; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment