首页 > 其他 > 详细

领扣382. Triangle Count

时间:2019-11-05 14:11:13      阅读:64      评论:0      收藏:0      [点我收藏+]

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)

领扣382. Triangle Count

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!