码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode Triangle Count

时间:2017-02-03 15:29:51      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:arrays   code   null   class   .so   ++   sum   while   man   

原题链接在这里: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

标签:arrays   code   null   class   .so   ++   sum   while   man   

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/6362616.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!