[leetcode-611-Valid Triangle Number]

Posted hellowOOOrld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-611-Valid Triangle Number]相关的知识,希望对你有一定的参考价值。

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]的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode]611. Valid Triangle Number有效三角数

LeetCode 611. Valid Triangle Number

model.trian()及model.eval()

LeetCode开心刷题五十一天——118. Pascal's Triangle 接触跳转表概念,不知用处 lamda逗号导致表达式加法奇怪不理解119. Pascal's Trian

[python]捕获ctrl+C事件后处理

补题多校联合训练第二场