[LeetCode]611. Valid Triangle Number

来源:互联网 发布:js json数组 某一个key 编辑:程序博客网 时间:2024/06/01 19:06

https://leetcode.com/problems/valid-triangle-number/#/description

找出满足组成三角形的三条边的个数


组成三角形条件是两条较短的边的和大于第三条边





public class Solution {    public int triangleNumber(int[] nums) {        if (nums == null || nums.length < 3) {            return 0;        }        Arrays.sort(nums);        int cnt = 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]) {                    cnt += r - l;                    r--;                } else {                    l++;                }            }        }        return cnt;    }}






原创粉丝点击