题目:
给定一个包含非负整数的数组,你的任务是统计其中可以组成三角形三条边的三元组个数。
示例 1:
输入: [2,2,3,4] 输出: 3 解释: 有效的组合是: 2,3,4 (使用第一个 2) 2,3,4 (使用第二个 2) 2,2,3
注意:
- 数组长度不超过1000。
- 数组里整数的范围为 [0, 1000]。
解题思路:
先对数组进行排序,优先确定最大的边长,然后寻找第二第三条边的范围。
也可以使用bfs对每个组合进行判断,但是很慢。
代码实现:
使用bfs检测(速度慢):
class Solution { private int count = 0; public int triangleNumber(int[] nums) { Arrays.sort(nums); dfs(nums, new int[3], 0, 0); return count; } private void dfs(int[] nums, int[] tri, int start, int line) { if (line == 3) { if (tri[0] + tri[1] > tri[2] && tri[1] + tri[2] > tri[0] && tri[0] + tri[2] > tri[1]) { count++; } return; } for (int i = start; i < nums.length; i ++) { tri[line] = nums[i]; dfs(nums, tri, i + 1, line + 1); tri[line] = 0; } } }
范围检测:
class Solution { public int triangleNumber(int[] nums) { if (nums == null || nums.length < 3) return 0; int cnt = 0; Arrays.sort(nums); for (int i = nums.length - 1; i >= 2; i --) { int l = 0; int r = i - 1; while (l < r) { if (nums[l] + nums[r] > nums[i]) { cnt += r - l; r --; } else { l ++; } } } return cnt; } }