leetcode:Array 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:

  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].

class Solution:
	def triangleNumber(self, nums):
		newlist = [ele for ele in nums if ele>0]               #列表中的元素必须大于0
		newlist.sort()
		length = len(newlist)
		count = 0
		for k in reversed(range(0,length)):                    #从最大的数开始
			i = 0
			j = k-1
			while i<j:
				if newlist[i]+newlist[j]>newlist[k]:    #如果[i]+[j]>[k]
					count += j-i                        #说明i到j-1的元素与j组合都符合要求,共j-i种
					j-=1		                        #说明我们可以适度减小[i]+[j],去i~j-1内找符合要求的数
				else:
					i+=1                                #如果不符合要求,那么我们必须增大[i]+[j]
		return count

猜你喜欢

转载自blog.csdn.net/w16337231/article/details/80145658