本文主要是介绍1132. 合法的三角数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
给定一个包含非负整数的数组,你的任务是计算从数组中选出的可以制作三角形的三元组数目,如果我们把它们作为三角形的边长。
样例
输入: [2,2,3,4]
输出: 3
解释:
合法的组合如下:
2,3,4 (使用第一个 2)
2,3,4 (使用第二个 2)
2,2,3
思路:
和之前做过的三数之和比较类似
第一种方法:可以暴力解决 但是时间复杂度O(n^3)
第二种方法:两指针的方法
public class Solution { /** * @param nums: the given array * @return: the number of triplets chosen from the array that can make triangles */ public int triangleNumber(int[] nums) { // Write your code here Arrays.sort(nums); int ans = 0; for(int i=0;i<nums.length-2;i++) { if(nums[i]==0)continue; int k=i+2; for(int j=i+1;j<nums.length-1;j++) { while(k<nums.length&&nums[k]<nums[i]+nums[j])k++; ans+=k-j-1; } } return ans; } }
这篇关于1132. 合法的三角数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!