問題:數組
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.ide
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:ip
解決:io
① 計算能夠組成三角形的三元組的個數。三角形的性質:任意兩條邊之和要大於第三邊。class
問題其實就變成了找出全部這樣的三個數字,使得任意兩個數字之和都大於第三個數字。那麼能夠轉變一下,三個數字中若是較小的兩個數字之和大於第三個數字,那麼任意兩個數字之和都大於第三個數字。sort
因此,將數組排序,先肯定前兩個數,將這兩個數之和sum做爲目標值,而後用二分查找法來快速肯定第一個小於目標值的數。make
class Solution { //62ms
public int triangleNumber(int[] nums) {
int res = 0;
int len = nums.length;
Arrays.sort(nums);
for (int i = 0;i < len;i ++){
for (int j = i + 1;j < len;j ++){
int sum = nums[i] + nums[j];
int left = j + 1;
int right = len;
while (left < right){
int mid = (right - left) / 2 + left;
if (nums[mid] < sum){
left = mid + 1;
}else {
right = mid;
}
}
res += right - 1 - j;
}
}
return res;
}
}while
② 使用二分查找查找較小的那兩個數,會簡單不少。co
class Solution { //26ms public int triangleNumber(int[] nums) { if (nums == null || nums.length == 0) return 0; int res = 0; int len = nums.length; Arrays.sort(nums); for (int i = 0;i < len;i ++){ int left = 0; int right = i - 1; while (left < right){ if (nums[left] + nums[right] > nums[i]){ res += right - left; right --; }else { left ++; } } } return res; } }