【Lintcode】382.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)]

题解:

  此类题目首先想到的是数组先排序(数组元素位置不影响结果,且题目与元素大小有关),最简单的是暴力搜索,三层循环。首先k从 2 遍历到 length(S)-1,内循环则为i和j枚举满足条件的情况。这里有个小技巧,因为我们首先对数组进行排序(从小到大),如例1,当S[k] = 7 时, i初始化为0,j初始化为k-1,那么有S[i] + S[j] > S[k],此时不需要再检查4+6>7的情况,因为3已经满足条件了,那么3以后的元素肯定也满足。这样就会减少大量的运算时间。一次遍历即可。

Solution 1 

class Solution {
public:
    int triangleCount(vector<int> &S) {
        int ans = 0;
        int len = S.size();
        if (len < 3) {
            return 0;
        }
        sort(S.begin(), S.end());
        for (int k = 2; k < len; ++k) {
            int i = 0; 
            int j = k - 1;
            while (i < j) {
                if (S[i] + S[j] > S[k]) {
                    ans += j - i;
                    j--;
                } else {
                    i++;
                }
            }
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/Atanisi/p/7003567.html