【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:
The length of the given array won’t exceed 1000.
The integers in the given array are in the range of [0, 1000].

解法

解法一:尺取法

假设a<=b<=c是三角形的三边,固定a,然后用尺取法枚举bc

class Solution(object):
    def triangleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        n = len(nums)
        ans = 0
        for i in xrange(n-2):
            r = i+2
            l = i+1
            while l<n-1:
                r = max(l+1, r)
                tar = nums[l]+nums[i]
                while r<n and nums[r]<tar:
                    r += 1
                ans += r-l-1
                l += 1
        return ans

解法二:固定c

参考:https://leetcode.com/problems/valid-triangle-number/discuss/199315/Python3-O(n2)-pointer-solution

解法一比较慢,可以固定c枚举ab,这样就转化成一个和twosum类似的问题了

class Solution(object):
    def triangleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        n = len(nums)
        ans = 0
        for i in xrange(2,n):
            l = 0
            r = i-1
            while r>l:
                if nums[l]+nums[r]>nums[i]:
                    # 如果和足够大,那么固定r,增加l时候的所有解都满足条件,而这样的l(包括l自己)一共有r-l个
                    ans += r-l
                    r -= 1
                else:
                    # 如果和太小了,那么增加和
                    l += 1
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值