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;
}
}