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

LeetCode:链接

这题和之前做过的3sum非常相似,是用排序+双指针做的,时间复杂度是O(n2)。

组成三角形的必备条件:任意两边之和大于第三边。但是,如果三个数字中较小的两个数字之和大于第三个数字,那么任意两个数字之和都大于第三个数字。

首先进行排序,然后从数字末尾从后往前进行遍历,将start指向首数字,end指向当前数字的前一个数字,如果start小于end就进行循环,循环里面判断如果start指向的数加上end指向的数大于当前的数字的话,那么right到left之间的数字都可以组成三角形,这是为啥呢,相当于此时确定了i和right的位置,可以将left向右移到right的位置,中间经过的数都大于left指向的数,所以都能组成三角形!加完之后,end自减一,即向左移动一位。如果left和right指向的数字之和不大于nums[i],那么start自增1,即向右移动一位。

class Solution(object):
    def triangleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        count = 0
        n = len(nums)
        for i in range(n-1, 1, -1):
            target = nums[i]
            low, high = 0, i-1
            while low < high:
                if nums[low] + nums[high] > target:
                    count += high - low
                    high -= 1
                else:
                    low += 1
        return count

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值