领扣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)
posted @ 2019-11-05 13:19  热锅上的码裔  阅读(117)  评论(0编辑  收藏  举报