LeetCode Valid Triangle Number

本文介绍了一道LeetCode上的算法题——如何计算给定数组中能组成三角形的数量。使用了双指针技巧,详细解释了解题思路及Java实现代码,并分析了时间复杂度和空间复杂度。

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

题目:

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

题解:

类似3Sum Smaller

也是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 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/7786436.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值