Description:
给定一个整数数组,在该数组中,寻找三个数,分别代表三角形三条边的长度,问,可以寻找到多少组这样的三个数来组成三角形?
Explanation:
例如,给定数组 S = {3,4,6,7},返回 3
其中我们可以找到的三个三角形为:
{3,4,6}
{3,6,7}
{4,6,7}
给定数组 S = {4,4,4,4}, 返回 4
其中我们可以找到的三个三角形为:
{4(1),4(2),4(3)}
{4(1),4(2),4(4)}
{4(1),4(3),4(4)}
{4(2),4(3),4(4)}
Solution:
Use three pointers, go through all the possible combinations, and judge whether it is a triangle.
public class Solution {
/**
* @param S: A list of integers
* @return: An integer
*/
public int triangleCount(int S[]) {
// write your code here
if(S == null || S.length < 3){
return 0;
}
int count = 0;
for(int i = 0 ; i< S.length - 2;i++){
for(int j = i + 1;j<S.length - 1;j++){
for(int k = j + 1;k<S.length;k++){
if(triangleJudge(S[i] , S[j] ,S[k])){
count++;
}
}
}
}
return count;
}
public boolean triangleJudge(int a, int b , int c){
if(a + b > c && a + c > b && b + c > a){
return true;
}else{
return false;
}
}
}
本文介绍了一种算法,用于从整数数组中找出所有能构成三角形的三个数的组合,并详细解释了实现过程。
1119

被折叠的 条评论
为什么被折叠?



