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].
题目链接:https://leetcode.com/problems/valid-triangle-number/
题目分析:第一眼的思路是二分,先排序,枚举前两个数的和,二分小于这个和的最后一个数的位置
23ms,时间击败23.38%
class Solution {
public int lastLessThan(int[] nums, int start, int x) {
int l = start, r = nums.length - 1, mid = 0, ans = -1;
while (l <= r) {
mid = (l + r) >> 1;
if (nums[mid] < x) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
return ans;
}
public int triangleNumber(int[] nums) {
Arrays.sort(nums);
int ans = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
int pos = lastLessThan(nums, j + 1, nums[i] + nums[j]);
if (pos > j) {
ans += pos - j;
}
}
}
return ans;
}
}
其实可以反着求,设第一大的为A,第二大的为B,第三大的为C,枚举A,B,二分C,找最后一个满足B+C>A的C的位置,如果不存在可以直接break
14ms,时间击败30.19%
class Solution {
public int binarySearch(int[] nums, int end, int fir, int sec) {
int l = 0, r = end, mid = 0, ans = -1;
while (l <= r) {
mid = (l + r) >> 1;
if (sec + nums[mid] > fir) {
ans = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
public int triangleNumber(int[] nums) {
Arrays.sort(nums);
int ans = 0;
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = i - 1; j >= 0; j--) {
int pos = binarySearch(nums, j - 1, nums[i], nums[j]);
if (pos != -1) {
ans += j - pos;
} else {
break;
}
}
}
return ans;
}
}
这题显然是有n^2解法的,主要从单调性上去考虑,不妨枚举C,A从0开始,B从C的前一位开始,如果此时A+B>C,说明A可以替换成[A, B-1]中的任何数,对答案的贡献为B-1-A+1=B-A,且此时可以尝试让B变得更小,反之只能通过增大A来满足上述不等式
4ms,时间击败99.73%
class Solution {
public int triangleNumber(int[] nums) {
if (nums.length < 3) {
return 0;
}
Arrays.sort(nums);
int ans = 0;
for (int c = nums.length - 1; c > 1; c--) {
int a = 0, b = c - 1;
while (a < b) {
if (nums[a] + nums[b] > nums[c]) {
ans += b - a;
b--;
} else {
a++;
}
}
}
return ans;
}
}