1. 程式人生 > >【Lintcode】382.Triangle Count

【Lintcode】382.Triangle Count

技巧 初始 運算 panel ron triangle ger numbers 暴力搜索

題目:

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

【Lintcode】382.Triangle Count