程序媛詹妮弗
终身学习

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

     

check if nums[left] + nums[right] > nums[k]  

         (1)YES.  Then we can say  (nums[left + 1] / nums[left + 2]....) + nums[right] > nums[k]

                            

                         So combination count: right - left

                         Then lock pointer k and pointer right -1 to get next combination count

            (2) No.   Then left ++

 

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 }

 

                          

 

posted on 2019-05-04 07:28  程序媛詹妮弗  阅读(205)  评论(0编辑  收藏  举报