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 @   Dylan_Java_NYC  阅读(150)  评论(0编辑  收藏  举报
编辑推荐:
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
阅读排行:
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
· 接口重试的7种常用方案!
历史上的今天:
2015-11-05 LeetCode Candy
2015-11-05 LeetCode 239. Sliding Window Maximum
2015-11-05 LeetCode 164. Maximum Gap
2015-11-05 LeetCode 273. Integer to English Words
点击右上角即可分享
微信分享提示