给定一个整数数组,在该数组中,寻找三个数,分别代表三角形三条边的长度,问,可以寻找到多少组这样的三个数来组成三角形?
例如,给定数组 S = {3,4,6,7}
,返回 3
其中我们可以找到的三个三角形为:
{3,4,6}
{3,6,7}
{4,6,7}
c++:一般而言,做ACM之类的题,不要考虑暴力搜索,有很大可能会超时,这个点考虑小技巧先sort,再,如例1,当S[k] = 7 时, i初始化为0,j初始化为k-1,那么有S[i] + S[j] > S[k],此时不需要再检查4+6>7的情况,因为3已经满足条件了,那么3以后的元素肯定也满足。这样就会减少大量的运算时间。一次遍历即可
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
/*
* @param S: A list of integers
* @return: An integer
*/
int i, j, k,count=0;
int triangleCount(vector<int> &S)
{
// write your code here
if (S.size() <= 2) return 0;
sort(S.begin(), S.end());
for (int k = 2; k < count; ++k) {
int i = 0;
int j = k - 1;
while (i < j) {
if (S[i] + S[j] > S[k]) {
count += j - i;
j--;
}
else {
i++;
}
}
}
return count;
}
};
int main()
{
Solution s1;
vector<int> s;
s.push_back(1);
s.push_back(2);
s.push_back(3);
s.push_back(4);
cout<< s1.triangleCount(s)<<endl;
system("pause");
return 0;
}
求助python版:关于主函数部分一直无法传递过去,求大牛留言解答
class Solution:
"""
@param: S: A list of integers
@return: An integer
"""
def triangleCount(self, S):
# write your code here
if S.len()<=2:
return 0
S.sort()
count = 0
for k in range( 2,S.len()):
i=0
j=k-1
while i<j:
if S[i] + S[j] > S[k]and S[i]+S[k]>S[j] and S[j]+S[k]>S[i]:
count += j-i
j=j-1
else:
i=i+1
return count
S=[]
S.append(3)
S.append(4)
S.append(6)
S.append(7)
s1=Solution()
s1.triangleCount(S)