Valid Triangle Number (第十六周 数组)

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.

For example,

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

算法思路

(1)其实这是一道签到题,快考试了,刷刷水题练练手感。
(2)给定一串数字,问能组成的三角形有多少组。
(3)那首先我们要知道给定三条边,如果验证这三条边能不能构成一个三角形。三角形的判断方法是任何两边之和大于第三边,两边之差小于第三边。那么我们就对于这3条边,任意的两两组合的边之和大于第三条边。
(4)然后我们就三重遍历这个数字数组,每重循环取出一条边,然后根据上面的方法判断能不能构成三角形。如果能,结果加一。

算法代码

class Solution {
public:
    int triangleNumber(vector<int>& nums) {
        int res = 0;
        int len = nums.size();
        for(int i = 0 ; i < len; i++)
            for(int j = i + 1; j < len; j++)
                for(int k = j + 1 ; k < len; k++)
                    if(istriangle(nums[i],nums[j],nums[k]))
                        res++;
        return res;
    }
    bool istriangle(int a, int b, int c){
        if(a + b > c && b + c > a && a + c > b)
            return true;
        else
            return false;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值