【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

你可能感兴趣的:(Leetcode)