题目:

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

解析:

首先如何判断三个边长能否组成一个三角形,这个初中数学就学过——两个小边的和大于最大边的边长。

def checkValid(self,a,b,c):
return (a+b) > c

因此,很容易得到解法,对nums数组排序后,做全排列,依次检查每种组合是否符合要求。

def triangleNumber2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
nums.sort()
for i in range(0,len(nums)-2):
for j in range(i+1,len(nums)-1):
for k in range(j+1,len(nums)):
if True == self.checkValid(nums[i], nums[j], nums[k]):
count += 1
#print nums[i], nums[j], nums[k]
else:
break
return count

但是非常遗憾,这种解法的复杂度是 O(n*3),超时了。根据判定中给出的超时输入发现,nums里面很多边长的数值是相同的。

Last executed input:
[33,97,81,65,30,58,83,83,66,85,78,40,51,61,86,94,42,17,35,18,45,27,56,78,36,97,6,51,76,26,68,68,61,87,13,98,93,80,24,34,19,90,85,89,83,15,41,52,25,16,61,51,19,6,40,79,25,88,65,85,0,42,78,27,30,68,47,67,40,26,15,72,20,45,88,82,12,82,95,1,46,56,83,20,65,39,13,92,36,99,74,50,46,8,27,45,36,55,50,0]

因此可以考虑优化算法,首先统计三个边长都不一样的情况,然后再考虑等腰三角形的情况,最后是等边三角形。

def triangleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#用一个list计数所有边长出线的次数,下标是边长值,对应的值是边长值出现的次数
count = 0
l = []
for i in range(0,1000+1):
l.append(0) for i in nums:
l[i] += 1
for i in range(1,len(l)-2):
if l[i] == 0:
continue
for j in range(i+1,len(l)-1):
if l[j] == 0:
continue
for k in range(j+1,len(l)):
if l[k] == 0:
continue
if True == self.checkValid(i,j,k):
count += (l[i]*l[j]*l[k])
else:
break
#dup
for i in range(1,len(l)):
if l[i] == 0 or l[i] == 1:
continue
else:
#print 'i:',i
#等腰三角形,如果某个边长值的出线的次数为n(n>=2),表示可以组成等腰三角形。根据组合的原理,两个腰可以得到C(2,n)
#然后根据 2*边长值与其他非自身边长值进行比较,得到等腰三角形的数量
for j in range(1,len(l)):
if 2*i > j and l[j] > 0 and j != i:
count += (l[i]*(l[i]-1))/2*l[j]
#等边三角形,这个也是组合,如果某个边长值的出线的次数为n(n>=3),表示可以组成等边三角形。
#根据组合的原理,可以等到的种数为C(3,n)
if l[i] >= 3:
count += (l[i]*(l[i]-1)*(l[i]-2))/6 return count

这样优化之后,效率得到了很大的提升,但是还是不够。进一步检查发现,list中无效的元素太多,可以考虑过滤掉很多边长值出现次数为0的元素,如代码所示,用一个ul对l中的数据进行过滤。

def triangleNumber3(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
l = []
for i in range(0,1000+1):
l.append(0) for i in nums:
l[i] += 1
#print l
ul = []
for i in range(0,len(l)):
if l[i] > 0:
ul.append(i)
#print ul
for i in range(0,len(ul)-2):
for j in range(i+1,len(ul)-1):
for k in range(j+1,len(ul)):
if True == self.checkValid(ul[i],ul[j],ul[k]):
count += (l[ul[i]]*l[ul[j]]*l[ul[k]])
#print i,j,k
else:
break
#dup
#print count
for i in range(0,len(ul)):
if l[ul[i]] == 0 or l[ul[i]] == 1 or ul[i] == 0:
continue
else:
#print 'i:',i
for j in range(0,len(ul)):
if 2*ul[i] > ul[j] and l[ul[j]] > 0 and j != i and ul[j] != 0:
#print (l[i]*(l[i]-1))/2
count += (l[ul[i]]*(l[ul[i]]-1))/2*l[ul[j]]
#print count
if l[ul[i]] >= 3:
count += (l[ul[i]]*(l[ul[i]]-1)*(l[ul[i]]-2))/6 return count

这样再一优化之后,终于通过了。

【leetcode】Valid Triangle Number的更多相关文章

  1. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  2. 【LeetCode】306. Additive Number 解题报告(Python)

    [LeetCode]306. Additive Number 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http: ...

  3. 【LeetCode】375. Guess Number Higher or Lower II 解题报告(Python)

    [LeetCode]375. Guess Number Higher or Lower II 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...

  4. 【LeetCode】137. Single Number II 解题报告(Python)

    [LeetCode]137. Single Number II 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/single- ...

  5. 【LeetCode】452. Minimum Number of Arrows to Burst Balloons 解题报告(Python)

    [LeetCode]452. Minimum Number of Arrows to Burst Balloons 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https ...

  6. Leetcode 之 Valid Triangle Number

    611. Valid Triangle Number 1.Problem Given an array consists of non-negative integers, your task is ...

  7. leetcode 611. Valid Triangle Number 、259. 3Sum Smaller(lintcode 918. 3Sum Smaller)

    这两个题几乎一样,只是说611. Valid Triangle Number满足大于条件,259. 3Sum Smaller满足小于条件,两者都是先排序,然后用双指针的方式. 611. Valid T ...

  8. 【leetcode】Valid Number

    Valid Number Validate if a given string is numeric. Some examples:"0" => true" 0.1 ...

  9. LeetCode 611. Valid Triangle Number有效三角形的个数 (C++)

    题目: Given an array consists of non-negative integers, your task is to count the number of triplets c ...

随机推荐

  1. 启动elasticsearch-head显示集群健康值:未连接

    ES启动后,进行es header访问的话,使用localhost:9100会显示集群健康值未连接 2种情况(均为windows10环境下): 1:未在elasticsearch-6.8.0\conf ...

  2. DSP28335 eCAP 测频

    F28335共有6组eCAP模块,每个eCAP不但具有捕获功能,而且还可用作PWM输出功能.F28335捕获模块的主要特征如下: 1. 150MHz系统时钟的情况下,32位时基的时间分辨率为6.67n ...

  3. Java 注解:@PostConstruct和@PreConstruct

    从Java EE5规范开始,Servlet增加了两个影响Servlet生命周期的注解(Annotation):@PostConstruct和@PreConstruct.这两个注解被用来修饰一个非静态的 ...

  4. Akka系列(七):Actor持久化之Akka persistence

    前言.......... 我们在使用Akka时,会经常遇到一些存储Actor内部状态的场景,在系统正常运行的情况下,我们不需要担心什么,但是当系统出错,比如Actor错误需要重启,或者内存溢出,亦或者 ...

  5. 创建可执行bin安装文件

    [应用场景] 简化操作,对于有些安装操作而言,需要包含安装脚本和脚本需要的文件两部分,封装成可执行bin文件之后就只有一个安装包了. 代码保护,在很多情况下,我们并不希望用户可以直接接触到代码部分,这 ...

  6. sql回显注入-笔记

     拼接sql命令查询数据   注释 常用于sql注入            # 井号 单行注释 注意:URL编码 %23          -- 两个减号加空格 单行注释           /*   ...

  7. mybatis generator 源码修改

    项目中使用mybatis + 通用mapper,用mybatis generator生成代码时有些不方便,参考了网上的一些例子,修改mybatis genrerator的源码. 首先,下载mybati ...

  8. [Python3] 031 常用模块 shutil & zipfile

    目录 shutil 1. shutil.copy() 2. shutil.copy2() 3. shutil.copyfile() 4. shutil.move() 5. 归档 5.1 shutil. ...

  9. [转帖]oracle备份恢复之recover database的四条语句区别

    oracle备份恢复之recover database的四条语句区别 https://www.cnblogs.com/andy6/p/5925433.html 需要学习一下. 1  recover d ...

  10. 你确定 SQL 查询都是以 SELECT 开始的?

    很多 SQL 查询都是以 SELECT 开始的. 不过,最近我跟别人解释什么是窗口函数,我在网上搜索"是否可以对窗口函数返回的结果进行过滤"这个问题,得出的结论是"窗口函 ...