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