Leetcode之Valid Triangle Number 问题
来源:互联网 发布:百度软件中心开发者 编辑:程序博客网 时间:2024/06/06 03:22
问题描述:
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.
Note:
- The length of the given array won't exceed 1000.
- The integers in the given array are in the range of [0, 1000].
示例:
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
问题来源:Valid Triangle Number (详细地址:https://leetcode.com/problems/valid-triangle-number/description/)
思路分析:题目的意思就是要找到三个能构成三角行的三个数,题目中的示例已经给出了一部分提示,数组必须是排好序的。所以我们先调用库函数sort()方法先排好序,接着我们启动三个指针:一个i作为遍历指针;一个low每次都从0开始,从左往右遍历;一个high每次都从i前面的一个位置出发,从右往左遍历。每次固定住i指针,我们比较nums[low] + nums[high]的大小和nums[i]的大小关系,既然是比较大小,那就有三种关系:
1.)nums[low] + nums[high] < nums[i],说明二者之和还是太小,那么我们的low指针就往右移动,即low++;
2.)nums[low] + nums[high] = nums[i],往常的思路这里就找到答案了,但是两边之和等于第三边能构成三角形吗?显然不行,所以和1.)是一个情形,low++;
3.)nums[low] + nums[high] > nums[i],这是我们希望看到的结果,但是结果应该是多少呢?其实位于low和high之间的元素都是成立的,为什么呢?你固定住high,想想low指向的数都满足条件,low右边的数还不能满足吗?这种情况i也要往左走了,因为i位于该位置的正确答案了啊。
代码:
- Leetcode之Valid Triangle Number 问题
- leetCode-Valid Triangle Number
- [LeetCode]611. Valid Triangle Number
- [LeetCode 611] Valid Triangle Number
- [LeetCode] 611. Valid Triangle Number
- [leetcode]611. Valid Triangle Number
- leetcode 611. Valid Triangle Number
- [leetcode] 611. Valid Triangle Number
- Leetcode:611. Valid Triangle Number
- leetcode 611. Valid Triangle Number
- 【LeetCode】611.Valid Triangle Number解题报告
- Leetcode之Valid Number
- Valid Triangle Number问题及解法
- 611. Valid Triangle Number
- leetcode611: Valid Triangle Number
- 611. Valid Triangle Number
- 611. Valid Triangle Number
- leetcode611. Valid Triangle Number
- bzoj1370 [Baltic2003]Gang团伙
- java.sql.SQLException: The Network Adapter could not establish the connection
- VS Code中转换大小写功能
- Linux安装教程--Ubuntu使用简单手册之安装篇
- GET、POST和HEAD的区别?
- Leetcode之Valid Triangle Number 问题
- 【C++】浅拷贝和深拷贝以及怎样实现一个简单的string类!!!
- 训练集---训练赛14
- 第3周项目4(1)- 顺序表应用
- Android UI 模板设计——Topbar
- 设计模式之代理模式
- 如何提高代码的健壮性需求?
- MySql索引(一)------初熟数据库索引
- SpringBoot集成MyBatis(主要用来方便的进行自定义一些sql查询,主要的简单的数据库操作还是依赖于自身提供的JPA)