[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;
    }
}

 

猜你喜欢

转载自www.cnblogs.com/Moriarty-cx/p/9941005.html