611. Valid Triangle Number #2218
-
Topics: Given an integer array Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the number of triplets in an array that can form a triangle. The key property of a triangle is that the sum of any two sides must be greater than the third side. Approach
Let's implement this solution in PHP: 611. Valid Triangle Number <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function triangleNumber($nums) {
sort($nums);
$count = 0;
$n = count($nums);
for ($k = $n - 1; $k >= 2; $k--) {
$i = 0;
$j = $k - 1;
while ($i < $j) {
if ($nums[$i] + $nums[$j] > $nums[$k]) {
$count += $j - $i;
$j--;
} else {
$i++;
}
}
}
return $count;
}
// Test cases
// Example 1
$nums1 = [2, 2, 3, 4];
echo triangleNumber($nums1) . "\n"; // Output: 3
// Example 2
$nums2 = [4, 2, 3, 4];
echo triangleNumber($nums2) . "\n"; // Output: 4
?> Explanation:
This approach efficiently narrows down the valid triplets by leveraging the sorted property and the two-pointer technique, ensuring an optimal solution with a time complexity of O(n²) due to the nested loops, which is efficient given the constraints. |
Beta Was this translation helpful? Give feedback.
We need to find the number of triplets in an array that can form a triangle. The key property of a triangle is that the sum of any two sides must be greater than the third side.
Approach