611. Valid Triangle Number
Input: nums = [2,2,3,4]
Output: 3
Explanation: Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3Input: nums = [4,2,3,4]
Output: 4Solution:
Last updated
Input: nums = [2,2,3,4]
Output: 3
Explanation: Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3Input: nums = [4,2,3,4]
Output: 4Last updated
public class Solution {
/**
* @param S: A list of integers
* @return: An integer
*/
public int triangleCount(int[] S) {
// write your code here
if (S == null || S.length < 3) {
return 0;
}
Arrays.sort(S);
int count = 0;
for (int i = 2; i < S.length; i++) {
count += getTriangleCount(S, i);
}
return count;
}
private int getTriangleCount (int[] S, int thirdIndex){
int count = 0;
int left = 0;
int right = thirdIndex - 1;
int thirdEdge = S[thirdIndex];
int sum;
while (left < right){
sum = S[left] + S[right];
if (sum > thirdEdge) {
count += right-left;
right--;
} else {
left++;
}
}
return count;
}
}