Triangle Count
Example
[3,4,6]
[3,6,7]
[4,6,7][4(1),4(2),4(3)]
[4(1),4(2),4(4)]
[4(1),4(3),4(4)]
[4(2),4(3),4(4)]Note
Code
Last updated
[3,4,6]
[3,6,7]
[4,6,7][4(1),4(2),4(3)]
[4(1),4(2),4(4)]
[4(1),4(3),4(4)]
[4(2),4(3),4(4)]Last updated
public class Solution {
/**
* @param nums: A list of integers
* @return: An integer
*/
public int triangleCount(int[] nums) {
// write your code here
if (nums == null || nums.length < 3) {
return 0;
}
Arrays.sort(nums);
int res = 0;
// 3 4 6 7 8
// i
// l r
for (int i = 2; i < nums.length; i++) {
int left = 0;
int right = i - 1;
while (left < right) {
if (nums[left] + nums[right] > nums[i]) {
res += right - left;
right--;
} else {
left++;
}
}
}
return res;
}
}