领扣382. Triangle Count

时间:2019-11-05
本文章向大家介绍领扣382. Triangle Count,主要包括领扣382. Triangle Count使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Description

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 1:

Input: [3, 4, 6, 7]
Output: 3
Explanation:
They are (3, 4, 6), 
         (3, 6, 7),
         (4, 6, 7)

Example 2:

Input: [4, 4, 4, 4]
Output: 4
Explanation:
Any three numbers can form a triangle. 
So the answer is C(3, 4) = 4

sort数组之后,固定最长边,另外两边用LintCode 609. Two Sum - Less than or equal to target一样的方法可以求得(详细解释见这里)。代码如下:
class Solution:
    """
    @param S: A list of integers
    @return: An integer
    """
    def twoSum5(self, nums, target):
        ans=0
        left,right=0,len(nums)-1
        while left<=right:
            while left<right and nums[left]+nums[right]<=target: left+=1
            ans+=right-left
            right-=1
        return(ans)
    
    def triangleCount(self, S):
        # write your code here
        if len(S)<3: return(0)
        S.sort()
        ans=0
        for j in range(2,len(S)):
            ans+=self.twoSum5(S[0:j], S[j])
        return(ans)

原文地址:https://www.cnblogs.com/Leisgo/p/11797798.html