• [LeetCode] 611. 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].

    题意:从一个数组中找出所有可能构造成三角形的个数

    首先我们来思考三角形的定义,两边之和大于第三边即可

    那么,既然考虑到了大小,数组,我们首先对数组进行排序。

    假设数组现在是

    1  2  3  4  5  6  7  8  9  10

    那么我们去搜数组可不可以构成三角形,必定得先定一点,去搜剩下两点。

    我们从大到小定点。i 从 9 -> 0

    那么对应元素也就是 10 - 1,为什么要这样做,因为最大边加其他边一定大于第三边,我们只需要考虑剩下两边之和是否大于最大边即可

    回到这里,我们采用双指针搜,由于i的位置已经有了,那么l = 0, r = i - 1

    如果满足 num[l] + num[r] > num[i] 

    那么之间会有r - l 个数字满足,比方说 2 + 9 > 10 ,那么 3到8 + 9都会大于10

    O(n*n) 的复杂度

    class Solution {
        public int triangleNumber(int[] nums) {
            if (nums.length < 3)
                return 0;
    
            Arrays.sort(nums);
            int sum = 0;
            for (int i = nums.length - 1; i >= 2; i--) {
                int l = 0;
                int r = i - 1;
                while (l < r) {
                    if (nums[l] + nums[r] > nums[i]) {
                        sum += r - l;
                        r --;
                    } else {
                        l ++;
                    }
                }
            }
            return sum;
        }
    }

     

  • 相关阅读:
    jquery 复制粘贴上传图片插件
    chrome插件的开发
    js获取剪切板内容,js控制图片粘贴
    记录前端常用的插件
    如何快速搭建node.js项目,app.js详解
    原型和原型链
    js 上传文件功能
    前端模块化开发发展史
    闭包实例
    5月8日疯狂猜成语-----对孔祥安组的测试版
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9941005.html
Copyright © 2020-2023  润新知