Rituo 611 The number of valid triangles
First of all, you need to know how to judge whether three numbers can form a triangle.
If there are three numbers a < b < c, if you want to form a triangle, you need to satisfy:
a+b > c ; a + c > b ; b + c > a ; Any two numbers greater than the third can form a triangle.
In fact, it is not difficult to find that if the three numbers are sorted from largest to smallest, it only needs to satisfy a+b > c.
So the first step first sorts the given array.
Secondly, fix the largest number as a side, and then use the double pointer left to point to the first number, and right to point to the previous number of the fixed largest number. When nums[left] + nums[right] > the fixed maximum number, move the right pointer to the right; otherwise, move the pointer left to the left.
Up to the fixed maximum number is the end position of the third number of the array. (problem-solving ideas)
So how to count the number of effective triangles?
class Solution {
public:
int triangleNumber(vector<int>& nums) {
//先给数组排序
sort(nums.begin(),nums.end());
int c = nums.size()-1;
int count = 0; // 记录有效三角形的个数
while(c>=2)
{
int left = 0, right = c-1;
while(left < right)
{
if(nums[left] +nums[right] > nums[c])
{
count += (right - left);
--right;
}else{
++left;
}
}
--c;
}
return count;
}
};