Valid Triangle Number (第十六周 数组)
来源:互联网 发布:python写入excel 编辑:程序博客网 时间:2024/06/06 13:11
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; }};
阅读全文
0 0
- Valid Triangle Number (第十六周 数组)
- 611. Valid Triangle Number
- leetcode611: Valid Triangle Number
- 611. Valid Triangle Number
- 611. Valid Triangle Number
- leetcode611. Valid Triangle Number
- 611. Valid Triangle Number
- 611. Valid Triangle Number
- 611. Valid Triangle Number
- 611. Valid Triangle Number
- 611. Valid Triangle Number
- 611. Valid Triangle Number
- leetCode-Valid Triangle Number
- 611. Valid Triangle Number
- [LeetCode]611. Valid Triangle Number
- [LeetCode 611] Valid Triangle Number
- [LeetCode] 611. Valid Triangle Number
- [leetcode]611. Valid Triangle Number
- mycati缓存cache
- akka实例
- 仿手机通讯录
- 动态规划实例(四):二项式系数问题
- 线程终止的方法
- Valid Triangle Number (第十六周 数组)
- 开源派
- JAVA 基础定义 day1
- 微信小程序实战篇-下拉刷新与加载更多
- 元编程结构控制
- python及scikit-learn的安装
- fastjson 使用 string字符串转换成java的各种类型
- 元编程算法示例
- 电商平台静态资源(图片)一般及CDN解决方案(转载)