611. Valid Triangle Number

来源:互联网 发布:vue.js 路由 编辑:程序博客网 时间:2024/06/07 10:17

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:

  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].



思路:

naive的思路是2层循环,外加一个Binary Search,复杂度O(N^2logN)

(要更快的话就是O(N^2),直接2层循环好像做不了什么事,那就先在外面一层循环,接着看能不能求出所有在该iteration下的所有可能情况,当然:外面循环的那个值不要随便假设,就假设为最后三角形的最大值好了)

可不可以只用一层循环呢?比如说固定最大的值,找另外2个加起来大于该最大值,这样就可以转化为在一个数组中求2个数加起来大于某个值的所有可能情况,很容易想到two pointer(是不是就是有点像3Sum,子不过3Sum是2个数加起来等于某个数,这里是2个数加起来大于某个数)

而且因为外套了一层循环,排序也不会影响到最后的复杂度


public class Solution {    public int triangleNumber(int[] nums) {        int count = 0;        Arrays.sort(nums);        for (int i = 0; i < nums.length - 2; i++) {            int k = i + 2;            for (int j = i + 1; j < nums.length - 1 && nums[i] != 0; j++) {                while (k < nums.length && nums[i] + nums[j] > nums[k])                    k++;                count += k - j - 1;            }        }        return count;    }}Complexity Analy