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

[leetcode-611-Valid Triangle Number]

时间:2017-06-11 13:45:57      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:can   bsp   class   etc   triangle   i++   pre   思路   triplets   

Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.

Example 1:

Input: [2,2,3,4]
Output: 3
Explanation:
Valid combinations are: 
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3

 

Note:

  1. The length of the given array won‘t exceed 1000.
  2. The integers in the given array are in the range of [0, 1000].

思路:

首先将数组排序。依次取出前两个边的长度。第三条边长度小于前两个边的和。

查找第三条边用二分查找。

int triangleNumber(vector<int>& a) {
      int i,j,k,n,left,right,mid,ans,sum;
      ans=0;
      sort(a.begin(),a.end());
      n=a.size();
      for (i=0;i<n;i++)
        for (j=i+1;j<n;j++)
        {
          sum=a[i]+a[j];
          left=j;right=n;
          while (right-left>1)
          {
            mid=(left+right)/2;
            if (a[mid]>=sum) right=mid;
            else left=mid;
          }
          ans+=left-j;
        }
      return ans;
    }

参考:

https://leetcode.com/lympanda/

[leetcode-611-Valid Triangle Number]

标签:can   bsp   class   etc   triangle   i++   pre   思路   triplets   

原文地址:http://www.cnblogs.com/hellowooorld/p/6984836.html

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