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.
Example 1:
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,3
Example 2:
Input: nums = [4,2,3,4] Output: 4
Constraints:
1 <= nums.length <= 10000 <= nums[i] <= 1000
代码(Rust):
impl Solution {
pub fn triangle_number(mut nums: Vec<i32>) -> i32 {
if nums.len() < 3 {
return 0;
}
let mut ans = 0;
nums.sort();
for i in 0..nums.len() - 2 {
for j in i + 1..nums.len() - 1 {
for k in j + 1..nums.len() {
if nums[i] + nums[j] > nums[k] {
ans += 1;
} else {
break;
}
}
}
}
ans
}
}
这是一篇关于LeetCode算法挑战的文章,讨论了如何从给定整数数组中找到可以构成三角形边长的三元组数量。文章提供了一个Rust代码实现。
8万+

被折叠的 条评论
为什么被折叠?



