Skip to content

Latest commit

 

History

History
88 lines (58 loc) · 1.52 KB

611.Valid_Triangle_Number.md

File metadata and controls

88 lines (58 loc) · 1.52 KB
  1. Valid Triangle Number 难度 中等

https://leetcode-cn.com/problems/valid-triangle-number/

Given an integer array nums, return 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: nums = [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

Example 2:

Input: nums = [4,2,3,4]
Output: 4
 

Constraints:

1 <= nums.length <= 1000
0 <= nums[i] <= 1000

相关企业

  • 字节跳动|6
  • 领英 LinkedIn|3
  • 微软 Microsoft|3
  • Shopee|3
  • 彭博 Bloomberg|2

相关标签

  • Greedy
  • Array
  • Two Pointers
  • Binary Search
  • Sorting

相似题目

3Sum Smaller 中等

solw solution: O(n^3)

count one by one

reduce dimension by batch processing O(n^2)

see ../note/plans_and_plan_count.md

class Solution:
    def triangleNumber(self, nums: List[int]) -> int:
        # If sorted (A <= B <= C) and A+B>C then it can be triangle.
        if not nums:
            return 0

        nums = sorted(nums)
        counter = 0

        for i in range(len(nums)):
            # A, B, C is nums[left], nums[right], nums[i]
            left, right = 0, i-1
            
            while left < right:
                if nums[left] + nums[right] > nums[i]:
                    counter += right - left # because sum of all elem [A, B) will > C
                    right -= 1
                else:
                    left += 1

        return counter