1. 程式人生 > >[leetcode]611. Valid Triangle Number有效三角數

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

exp span ets == greate pan 題意 for sim

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)

[2,  2,  3,  4]

^k

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

[2,  2,  3,  4]

^k

^left ^right

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 }

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