领扣382. Triangle Count

…衆ロ難τιáo~ 提交于 2019-12-03 13:52:32

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) = 4sort数组之后,固定最长边,另外两边用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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!