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 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/6362616.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值