382. Triangle Count-三角形计数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lighthear/article/details/79764398

Description

给定一个整数数组,在该数组中,寻找三个数,分别代表三角形三条边的长度,问,可以寻找到多少组这样的三个数来组成三角形?

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

Given array S = [3,4,6,7], return 3. They are:

[3,4,6]
[3,6,7]
[4,6,7]

Given array S = [4,4,4,4], return 4. They are:

[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

解题思路:

1. a < b < c && a + b > c ,三角形的判断条件是两个最短的边之和大于第三条边,类似Three-Sum问题

2. 遍历最大的边,在0到i - 1之间找到a + b > c的组合

3. 如果S[left] + S[right] > S[i]则left从当前位置加到right的位置之间都满足此条件

public class Solution {
    /**
     * @param S: A list of integers
     * @return: An integer
     */
    public int triangleCount(int[] S) {
        // write your code here
        //a < b < c && a + b > c
        //判断条件是两个最短的边之和大于第三条边,类似Three-Sum问题
        if (S == null || S.length < 3) {
            return 0;
        }
        Arrays.sort(S);
        int count = 0;
        //循环最大的边,在0到i - 1之间找到a + b > c的组合
        for (int i = 0; i < S.length; i++) {
            int left = 0, right = i - 1;
            while (left < right) {
                if (S[left] + S[right] > S[i]) {
                    //如果S[left] + S[right] > S[i]则left从当前位置加到right的位置之间都满足此条件
                    count = count + right - left;
                    right--;
                } else {
                    left++;
                }
            }
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/lighthear/article/details/79764398