这篇文章是程序自动发表的,详情可以见
这里
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
这是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. 思路 注意只要三角形的最大边小于另两边之和,所以排序后,进行搜索,避免不必要的比较
show me the code
class Solution: def triangleNumber(self, nums): """ :type nums: List[int] :rtype: int """ ct = 0 nums.sort() n = len(nums) for i in range(2,n): lo , hi = 0,i-1 while lo < hi: if nums[lo] nums[hi]>nums[i]: ct =hi-lo hi-=1 else:lo =1 return ct