website/content.en/ChapterFour/0600~0699/0611.Valid-Triangle-Number.md
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.
Given an array containing non-negative integers, your task is to count the number of triplets that can form the three sides of a triangle.
nums[i] + nums[j] > nums[k]; then all values in the interval [nums[j + 1], nums[k - 1]] satisfy the condition. The number of valid solutions increases by k - j - 1. Then j increments by 1 again. At this point, the innermost k does not need to start from j + 1; it only needs to continue from the previous k. Because if nums[i] + nums[j] > nums[k], and if the inequality nums[i] + nums[j + 1] > nums[m + 1] holds, then m must be no smaller than k. Therefore, the combined time complexity of the inner loops k and j is O(n), and the outermost loop i is O(n). After this optimization, the overall time complexity is O(n^2).a + b > c, a + c > b, b + c > a. Why do we only check a + b > c here? Because the array is sorted at the beginning, so a ≤ b ≤ c. Under this premise, a + c > b and b + c > a must hold. Therefore, the original problem is transformed into only needing to care whether the single inequality a + b > c holds. The test cases for this problem include a special case where one side or two sides have length 0, in which case the inequality a + b > c definitely does not hold. In summary, after sorting as preprocessing, we only need to care whether the inequality a + b > c holds.package leetcode
import "sort"
func triangleNumber(nums []int) int {
res := 0
sort.Ints(nums)
for i := 0; i < len(nums)-2; i++ {
k := i + 2
for j := i + 1; j < len(nums)-1 && nums[i] != 0; j++ {
for k < len(nums) && nums[i]+nums[j] > nums[k] {
k++
}
res += k - j - 1
}
}
return res
}