triangle count
Given an array of integers, how many three numbers can be found in the array, so that we can build an triangle whose three edges length is the three numbers that we find?
Example
Given array S = [3,4,6,7], return 3. They are:
[3,4,6]
[3,6,7]
[4,6,7]
Given array S = [4,4,4,4], return 4. They are:
[4(1),4(2),4(3)]
[4(1),4(2),4(4)]
[4(1),4(3),4(4)]
[4(2),4(3),4(4)]
解法一
暴力
public class Solution {
/*
* @param S: A list of integers
* @return: An integer
* @time: O(n^3)
* @space: O(1)
*/
public int triangleCount(int[] S) {
// write your code here
Arrays.sort(S);
int ans = 0;
for (int i = 0; i < S.length; i++) {
for (int j = 0; j < i; j++) {
for (int k = 0; k < j; k++) {
if (S[j] + S[k] > S[i]) {
ans++;
}
}
}
}
return ans;
}
}
解法二
双指针法
public class Solution {
/*
* @param S: A list of integers
* @return: An integer
* @time: O(nlogn + n^2)
* @space: O(1)
*/
public int triangleCount(int[] S) {
// write your code here
Arrays.sort(S);
int ans = 0;
for (int i = 0; i < S.length; i++) {
int left = 0, right = i - 1;
while (left < right) {
if (S[left] + S[right] > S[i]) {
ans += right - left;
right--;
} else {
left++;
}
}
}
return ans;
}
}

本文介绍了一种在整数数组中寻找能构成三角形的三元组数量的算法。通过两种方法实现:一种是时间复杂度为O(n³)的暴力解法;另一种是结合排序与双指针技巧的时间复杂度为O(n²logn)的优化解法。
1312

被折叠的 条评论
为什么被折叠?



