leetCode-Valid Triangle Number

来源:互联网 发布:深入浅出数据分析 txt 编辑:程序博客网 时间:2024/05/29 18:35

Description:
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: 3Explanation:Valid combinations are: 2,3,4 (using the first 2)2,3,4 (using the second 2)2,2,3

Note:

    The length of the given array won't exceed 1000.    The integers in the given array are in the range of [0, 1000].

Solution:

//先给nums排序,定3个指针,first,second,last(i相当于last),从右往左迭代last,如果nums[first]+nums[second]>nums[last],则first到second之间的都满足,递减second,否则,递增firstclass Solution {    public int triangleNumber(int[] nums) {            if(nums == null || nums.length <= 2){                return 0;            }            java.util.Arrays.sort(nums);            int len = nums.length;            int count = 0;            for(int i = len - 1;i >= 2;i--){                int first = 0;int second = i - 1;                while(first != second){                    if(nums[first] + nums[second] > nums[i]){                        count += second - first;                        second --;                    }else{                        first++;                    }                }            }            return count;    }}
原创粉丝点击