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)。

  • 相关阅读:
    onkeyup事件
    asp.net学习视频资料地址链接
    企业站新闻信息的后台功能开发心得(1)
    js实现切换导航
    jquery实现上拉加载更多
    css设置input框没有边框,选中时取消背景色
    使用js修改url地址参数
    ubantu 修改hosts文件
    git的使用
    ubantu 16.04 菜单栏的位置变换
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5563955.html
Copyright © 2011-2022 走看看