Triangle Count
程序员文章站
2022-03-11 21:49:33
...
Given an array of integers, how many three numbers can be found in the array, so that we can build an triangle whose three edges length is the three numbers that we find?
Example
Example 1:
Input: [3, 4, 6, 7]
Output: 3
Explanation:
They are (3, 4, 6),
(3, 6, 7),
(4, 6, 7)
Example 2:
Input: [4, 4, 4, 4]
Output: 4
Explanation:
Any three numbers can form a triangle.
So the answer is C(3, 4) = 4
思路:构成三角形的条件是:任意两边之和大于第三边;
那么我固定最长边A[i] ,剩下的任务就是从0 ~ i -1 找到两个数,和要大于A[i];
public class Solution {
/**
* @param S: A list of integers
* @return: An integer
*/
public int triangleCount(int[] S) {
if(S == null || S.length == 0) {
return 0;
}
Arrays.sort(S);
int count = 0;
for(int i = 0; i < S.length; i++) {
int left = 0;
int right = i - 1;
while(left < right) {
if(S[left] + S[right] > S[i]) {
count += right - left;
right--;
} else {
left++;
}
}
}
return count;
}
}
上一篇: 注意!朋友圈里兜售疫苗是违法行为
下一篇: codeforces 补题总结 2
推荐阅读
-
数据select count时多个字段确定唯一的问题_MySQL
-
cursor_sharing=similar参数引起version_count high|libra
-
Oracle count(*)是否走索引
-
PHP中substr_count()函数获取子字符串出现次数的方法,phpsubstr_count
-
PHP源代码数组统计count分析
-
php中count 多维数组长度统计实现方法
-
php中count获取多维数组长度的方法
-
Codeforces 1398 A. Bad Triangle(水题)
-
【OpenGL ES】Hello Triangle
-
mysql found_row()与row_count()实例讲解