Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
If we sort the array, for every pair (i, j), we can find the largest k such that nums[i] + nums[j] > nums[k]. This allows us to count valid triangles efficiently.
classSolution {
publicinttriangleNumber(int[] nums) {
Arrays.sort(nums);
int n = nums.length, count = 0;
for (int k = n - 1; k >= 2; k--) {
int i = 0, j = k - 1;
while (i < j) {
if (nums[i]+ nums[j]> nums[k]) {
count += (j - i);
j--;
} else {
i++;
}
}
}
return count;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funtriangleNumber(nums: IntArray): Int {
nums.sort()
var count = 0for (k in nums.size - 1 downTo 2) {
var i = 0var j = k - 1while (i < j) {
if (nums[i] + nums[j] > nums[k]) {
count += (j - i)
j-- } else {
i++ }
}
}
return count
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from typing import List
classSolution:
deftriangleNumber(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
count =0for k in range(n-1, 1, -1):
i, j =0, k-1while i < j:
if nums[i] + nums[j] > nums[k]:
count += (j - i)
j -=1else:
i +=1return count