首页 > 代码库 > LintCode Triangle Count

LintCode Triangle Count

原题链接在这里:http://www.lintcode.com/en/problem/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)]

题解:

与3Sum Smaller类似.

也是Two Pointers, 构成三角要求三条边成a + b > c. 设S[i] 为c, 前面的数中选出S[l]为a, S[r]为b. 

若是S[l] + S[r] > c则符合要求,还会有会有r-l种组合若继续向右移动l. 所以res += r-l. r左移一位.

若是S[l] + S[r] <= c, 则向右移动l.

Time Complexity: O(n^2). sort 用时O(nlogn), 对于每一个c, Two Points用时O(n). n = S.length.

Space: O(1).

AC Java:

 1 public class Solution {
 2     public int triangleCount(int S[]) {
 3         if(S == null || S.length < 3){
 4             return 0;
 5         }
 6         
 7         int res = 0;
 8         Arrays.sort(S);
 9         for(int i = 2; i<S.length; i++){
10             int l = 0;
11             int r = i-1;
12             while(l<r){
13                 if(S[l] + S[r] > S[i]){
14                     res += r-l;
15                     r--;
16                 }else{
17                     l++;
18                 }
19             }
20         }
21         return res;
22     }
23 }

 

LintCode Triangle Count