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 sort(self, nums):
        start = 0
        end = len(nums) - 1
        self.partition(nums, start, end)
        return nums

    def partition(self, nums, start, end):
        if end <= start:
            return start
        index1, index2 = start, end
        base = nums[start]
        while start < end:
            while start < end and nums[end] >= base:
                end -= 1
            nums[start] = nums[end]
            while start < end and nums[start] <= base:
                start += 1
            nums[end] = nums[start]
        nums[start] = base
        self.partition(nums, index1, start-1)
        self.partition(nums, start+1, index2)

    def triangleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums = self.sort(nums)
        n = len(nums)
        count = 0
        '''从数字末尾开始遍历'''
        for i in range(n-1, 1, -1):
            j, k = 0, i-1
            while j < k:
                if nums[j] + nums[k] > nums[i]:
                    count += k - j
                    k -= 1
                else:
                    j += 1
        return count

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/84344865