原文链接: https://leetcode-cn.com/problems/valid-triangle-number
英文原文
Given an integer array nums
, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
Example 1:
Input: nums = [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
Example 2:
Input: nums = [4,2,3,4] Output: 4
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] <= 1000
中文题目
给定一个包含非负整数的数组,你的任务是统计其中可以组成三角形三条边的三元组个数。
示例 1:
输入: [2,2,3,4] 输出: 3 解释: 有效的组合是: 2,3,4 (使用第一个 2) 2,3,4 (使用第二个 2) 2,2,3
注意:
- 数组长度不超过1000。
- 数组里整数的范围为 [0, 1000]。
通过代码
高赞题解
解题思路:
判断三条边能组成三角形的条件为:
任意两边之和大于第三边,任意两边之差小于第三边。
三条边长从小到大为 a、b、c,当且仅当
a + b > c
这三条边能组成三角形。
方法一 :暴力
三重循环枚举。
时间复杂度为 $O(n^3)$,可能会超时。
方法二:二分查找
首先对数组排序。
固定最短的两条边,二分查找最后一个小于两边之和的位置。可以求得固定两条边长之和满足条件的结果。枚举结束后,总和就是答案。
时间复杂度为 $O(n^2logn)$。
[-Java]class Solution { public int triangleNumber(int[] nums) { Arrays.sort(nums); int n = nums.length; int res = 0; for (int i = 0; i < n - 2; ++i) { for (int j = i + 1; j < n - 1; ++j) { int s = nums[i] + nums[j]; int l = j + 1, r = n - 1; while (l < r) { int mid = l + r + 1 >>> 1; if (nums[mid] < s) l = mid; else r = mid - 1; } if (nums[r] < s) { res += r - j; } } } return res; } }
方法三:双指针
首先对数组排序。
固定最长的一条边,运用双指针扫描
如果
nums[l] + nums[r] > nums[i]
,同时说明nums[l + 1] + nums[r] > nums[i], ..., nums[r - 1] + nums[r] > nums[i]
,满足的条件的有r - l
种,r
左移进入下一轮。如果
nums[l] + nums[r] <= nums[i]
,l
右移进入下一轮。
枚举结束后,总和就是答案。
时间复杂度为 $O(n^2)$。
[-Java]class Solution { public int triangleNumber(int[] nums) { Arrays.sort(nums); int n = nums.length; int res = 0; for (int i = n - 1; i >= 2; --i) { int l = 0, r = i - 1; while (l < r) { if (nums[l] + nums[r] > nums[i]) { res += r - l; --r; } else { ++l; } } } return res; } }
统计信息
通过次数 | 提交次数 | AC比率 |
---|---|---|
53188 | 99882 | 53.3% |
提交历史
提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
---|
相似题目
题目 | 难度 |
---|---|
较小的三数之和 | 中等 |