[leetcode]611. Valid Triangle Number有效三角数

匿名 (未验证) 提交于 2019-12-02 23:32:01

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

题意:

给定数组,可由数组中的数字组成多少个valid三角形

解本题的背景知识: 【Math fact】The sum of two sides of a triangle must be greater than the third one

Solution1: Two Pointers (similar as 3 Sum problem)

1. sort array

2. lock pointer k at the trail (must be largest side)

3. set pointer left at 0, right at k-1

Lock pointer k and pointer right

code

 1 /*  2 Time: O(n^2)  3 Space: O(1)  4 */  5   6 class Solution {  7     public int triangleNumber(int[] nums) {  8         if(nums == null || nums.length == 0) return 0;  9         Arrays.sort(nums);   10         int result = 0; 11          for (int k = nums.length - 1; k > 0 ; k--) { 12             int left = 0; 13             int right = k - 1 ; 14             while (left < right) { 15                 if (nums[left] + nums[right] > nums[k]) { 16                     result += (right - left); 17                     right--; 18                 } 19                 else { 20                     left++; 21                 } 22             } 23         }  24         return result; 25     } 26 }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!