版权声明:本文为博主原创文章,欢迎转载!转载请保留原博客地址。 https://blog.csdn.net/grllery/article/details/88094299
611. Valid Triangle Number
Given an array consists of non-negative integers, your task is to count 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: [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
Note:
The length of the given array won't exceed 1000.
The integers in the given array are in the range of [0, 1000].
题目:给定一个数组,判断有多少种可以组成三角形的三元组。
思路:参考解析。首先三角形的条件是任意两边之和大于第三边,即a+b>c
,a+c>b
和c+b>a
,有三个判断条件。直接暴力循环的话TLE
。对数组nums
进行排序后判断条件就可以缩减为1个a+b>c
,原因在于排序后c>b
,c>a
,那么在不等式左侧加上一个正数,还是满足条件的。用first
、second
表示两个短边所在的序号,third
表示长边所在的序号。那么针对nums[third]
这个长边,两个短边肯定都在其左侧(因为nums
排过序了),令first
从序号0开始,second
从序号third-1
开始,那么我们可以不断的调整这两个短边直到他们相遇为主。调整的原则是,如果nums[first] + nums[second] > nums[third]
,说明我们已经找到了一种三角形,此时因为固定second
的位置,然后不断增加first
,肯定都是满足上述的判断的,此时对应的三角形的个数为second - first
,所以我们更新second
的位置。
class Solution {
public:
int triangleNumber(vector<int>& nums) {
sort(nums.begin(), nums.end());
int len = nums.size();
int cnt = 0;
for(int third = len - 1; third >= 2; --third){
int first = 0;
int second = third - 1;
while(first < second){
if(nums[first] + nums[second] > nums[third]){
//<first, second, third> such that first + second > third, there is no need to increment first
cnt += (second - first);
--second;
}
else
++first;
}
}
return cnt;
}
};