- Triangle Count
中文English
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
Example 1:
Input: [3, 4, 6, 7]
Output: 3
Explanation:
They are (3, 4, 6),
(3, 6, 7),
(4, 6, 7)
Example 2:
Input: [4, 4, 4, 4]
Output: 4
Explanation:
Any three numbers can form a triangle.
So the answer is C(3, 4) = 4
解法1:三指针法,类似3sum。先排序。p3从2到n-1。p1每次从0到p3-2,其间每次p2=p3-1,若S[p1]+S[p2]>S[p3],则count++, p2–。该方法时间复杂度高,约为O(n^3)。
代码如下:
class Solution {
public:
/**
* @param S: A list of integers
* @return: An integer
*/
int triangleCount(vector<int> &S) {
int n = S.size();
if (n < 3) return 0;
int p1 = 0, p2 = 1, p3 = 2;
int count = 0;
sort(S.begin(), S.end());
while(p3 < n) {
p1 = 0;
while(p1 < p3 - 1) {
p2 = p3 - 1;
while(p1 < p2) {
if ((S[p1] + S[p2]) > S[p3]) {
p2--;
count++;
} else {
break;
}
}
p1++;
}
p3++;
}
return count;
}
};
解法2:解法1的基础上加上binary search。复杂度O(n^2logn)。
代码如下:
class Solution {
public:
/**
* @param S: A list of integers
* @return: An integer
*/
int triangleCount(vector<int> &S) {
int n = S.size();
if (n < 3) return 0;
int start = 0, end = 2;
int count = 0;
sort(S.begin(), S.end());
while(end < n) {
start = 0;
while(start < end - 1) {
int pos = binarySearch(S, start + 1, end - 1, S[end] - S[start]);
if (pos > 0) count += end - pos;
start++;
}
end++;
}
return count;
}
private:
//find the 1st pos such that S[start] + S[pos] > S[end], that is, S[start] + S[pos - 1] <= S[end]
int binarySearch(vector<int> &S, int start, int end, int target) {
while(start + 1 < end) {
int mid = start + (end - start) / 2;
if (S[mid] > target) {
end = mid;
} else {
start = mid;
}
}
if (S[start] > target) return start;
if (S[end] > target) return end;
return -1;
}
};
解法3:类似3sum的解法。
该解法更好,时间复杂度O(n^2)。
思路:start = 0, end = pos - 1。每次当S[start]+S[end]>S[pos]时,count+=end-start,即A=(start…end-1), B=end,C=pos这3点的三角形个数。然后B–,此时又可以统计新的B,C和不同的A所构成的三角形了。
代码如下:
class Solution {
public:
/**
* @param S: A list of integers
* @return: An integer
*/
int triangleCount(vector<int> &S) {
int n = S.size();
if (n < 3) return 0;
int count = 0;
sort(S.begin(), S.end());
for (int pos = 2; pos < n; ++pos) {
int start = 0, end = pos - 1;
while (start < end) {
if ((S[start] + S[end]) > S[pos]) {
count += end - start;
end--;
} else {
start++;
}
}
}
return count;
}
};