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.
Example 1:
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
Note:
- The length of the given array won’t exceed 1000.
- The integers in the given array are in the range of [0, 1000].
題意:給出數列nums,求隨機取3個數能夠組成的三角形的個數。
滿足三角形:兩條小邊的和大於大邊,因此首先進行排序。
重點:三重循環確定三邊,最大邊用二分法確定(當時面試時死活都沒有想到的優化。。。。。。。)。
代碼如下:
class Solution {
public int triangleNumber(int[] nums) {
Arrays.sort(nums);
int n=nums.length;
int count=0;
for(int i=0;i<n-2;i++)
{
for(int j=i+1;j<n-1;j++)
{
int l=j;
int r=n;
while(l+1<r){
int mid=(l+r)/2;
if(nums[i]+nums[j]<=nums[mid])
r=mid;
else
l=mid;
}
count+=l-j;
}
}
return count;
}
}