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 <= 1000
0 <= nums[i] <= 1000
Solutions
Solution 1: Sorting + Binary Search
A valid triangle must satisfy: the sum of any two sides is greater than the third side. That is:
\[a + b \gt c \tag{1}\]
\[a + c \gt b \tag{2}\]
\[b + c \gt a \tag{3}\]
If we arrange the sides in ascending order, i.e., \(a \leq b \leq c\), then obviously conditions (2) and (3) are satisfied. We only need to ensure that condition (1) is also satisfied to form a valid triangle.
We enumerate \(i\) in the range \([0, n - 3]\), enumerate \(j\) in the range \([i + 1, n - 2]\), and perform binary search in the range \([j + 1, n - 1]\) to find the first index \(left\) that is greater than or equal to \(nums[i] + nums[j]\). Then, the values of \(k\) in the range \([j + 1, left - 1]\) satisfy the condition, and we add them to the result \(\textit{ans}\).
The time complexity is \(O(n^2\log n)\), and the space complexity is \(O(\log n)\), where \(n\) is the length of the array.