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.
#include<vector>#include<algorithm>usingnamespace std;
inttriangleNumber(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size(), 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;
}
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
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
deftriangleNumber(nums):
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
pubfntriangle_number(mut nums: Vec<i32>) -> i32 {
nums.sort();
let n = nums.len();
letmut count =0;
for k in (2..n).rev() {
let (mut i, mut j) = (0, k -1);
while i < j {
if nums[i] + nums[j] > nums[k] {
count += (j - i) asi32;
j -=1;
} else {
i +=1;
}
}
}
count
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
functiontriangleNumber(nums: number[]):number {
nums.sort((a, b) =>a-b);
letcount=0;
for (letk=nums.length-1; k>=2; k--) {
leti=0, j=k-1;
while (i<j) {
if (nums[i] +nums[j] >nums[k]) {
count+= (j-i);
j--;
} else {
i++;
}
}
}
returncount;
}