LeetCode 611. Valid Triangle Number

原题链接在这里:https://leetcode.com/problems/valid-triangle-number/

题目:

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

题解:

也是Two Pointers, 构成三角要求三条边成a + b > c. 设nums[i] 为c, 前面的数中选出nums[l]为a, nums[r]为b. 

若是nums[l] + nums[r] > c则符合要求,若继续向右移动l, 有r-l种组合都包括num[r]. 所以res += r-l. r左移一位, 之后可能还有符合条件的组合.

若是nums[l] + nums[r] <= c, 则向右移动l.

Time Complexity: O(n^2). sort 用时O(nlogn), 对于每一个c, Two Points用时O(n). n = nums.length.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int triangleNumber(int[] nums) {
 3         if(nums == null || nums.length == 0){
 4             return 0;
 5         }
 6         
 7         int res = 0;
 8         Arrays.sort(nums);
 9         for(int i = 2; i<nums.length; i++){
10             int l = 0;
11             int r = i-1;
12             while(l<r){
13                 if(nums[l] + nums[r] > nums[i]){
14                     res += r-l;
15                     r--;
16                 }else{
17                     l++;
18                 }
19             }
20         }
21         return res;
22     }
23 }

类似3Sum Smaller.  

posted @ 2017-11-05 06:00  Dylan_Java_NYC  阅读(149)  评论(0编辑  收藏  举报