zoukankan      html  css  js  c++  java
  • Triangle Count

    Given an array of integers, how many three numbers can be found in the array, so that we can build an triangle whose three edges length is the three numbers that we find?

    Given array S = [3,4,6,7], return 3. They are:

    [3,4,6]
    [3,6,7]
    [4,6,7]
    

    Given array S = [4,4,4,4], return 4. They are:

    [4(1),4(2),4(3)]
    [4(1),4(2),4(4)]
    [4(1),4(3),4(4)]
    [4(2),4(3),4(4)]

    Lintcode上的一道题目,刚开始看到并没有什么思路,仔细分析下还是可以看到解题思路的。已知三条边a,b,c,则判断它们能不能组成三角形的条件是:a + b> c&&

    a + c > b && b + c > a。约束条件还是非常多的。 但是如果 a,b,c已经排序,比如a<b<c, 则只需判断a+b > c。大大简化约束。所以这题可以对数组先进行排序。

    之后我们相对固定第三条边,然后用双指针进行另外两条边的扫描,寻找a + b > c的 <a,b> pair。这步其实就是Two Sum II 所要做的事情。从右往左扫第三条边,在其左边的数组用双指针查找合格pair。代码如下:

    class Solution:
        # @param S: a list of integers
        # @return: a integer
        def triangleCount(self, S):
            if not S or len(S) < 3:
                return 0
            S.sort()
            res = 0
            for i in xrange(len(S)-1, 1 ,-1):
                left = 0
                right = i -1
                while left < right:
                    if S[left] + S[right] > S[i]:
                        res += right - left
                        right -= 1
                    else:
                        left += 1
            return res

    排序时间复杂度为O(nlogn)。其后的时间复杂度为O(n^2)。所以总体的时间复杂度为O(n^2),空间复杂度为O(1)。

  • 相关阅读:
    JAVA BigDecimal 小数点处理
    对 Element UI table中数据进行二次处理
    Kettle-User Defined Java Class使用-大写转换
    多线程-同步函数
    多线程-银行分批存款
    多线程-并发卖票
    多线程-控制两个线程交替打印
    ztree-可拖拽可编辑的树
    ztree-编辑节点(树节点添加,删除,修改)
    ztree-拖拽(排序树)
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5563955.html
Copyright © 2011-2022 走看看