leetcode02 Triangle Count

本文介绍了一种在整数数组中寻找能构成三角形的三元组数量的算法。通过两种方法实现:一种是时间复杂度为O(n³)的暴力解法;另一种是结合排序与双指针技巧的时间复杂度为O(n²logn)的优化解法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

triangle count

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)]

解法一

暴力

public class Solution {
    /*
     * @param S: A list of integers
     * @return: An integer
     * @time: O(n^3)
     * @space: O(1)
     */
    public int triangleCount(int[] S) {
        // write your code here
        Arrays.sort(S);
        int ans = 0;
        for (int i = 0; i < S.length; i++) {
            for (int j = 0; j < i; j++) {
                for (int k = 0; k < j; k++) {
                    if (S[j] + S[k] > S[i]) {
                        ans++;
                    }
                }
            }
        }

        return ans;
    }
}

解法二

双指针法

public class Solution {
    /*
     * @param S: A list of integers
     * @return: An integer
     * @time: O(nlogn + n^2)
     * @space: O(1)
     */
    public int triangleCount(int[] S) {
        // write your code here
        Arrays.sort(S);
        int ans = 0;

        for (int i = 0; i < S.length; i++) {
            int left = 0, right = i - 1;
            while (left < right) {
                if (S[left] + S[right] > S[i]) {
                    ans += right - left;
                    right--;
                } else {
                    left++;
                }
            }
        }

        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值