1. 程式人生 > >LeetCode611:Valid Triangle Number

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