611. Valid Triangle Number

来源:互联网 发布:剑灵捏脸数据如何保存 编辑:程序博客网 时间:2024/06/07 15:03
# 611. Valid Triangle Number标签(空格分隔): leetcode array medium—# 题目
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: 3Explanation: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].


思路

本题判断的规则是最小两边之和大于第三边。我们实现了一个时间复杂度为O(n2),空间复杂度为O(1)的方法。基本思路就是先排序,再维护头尾指针遍历。

代码

class Solution {public:    int triangleNumber(vector<int>& nums) {        //step1:先排序        sort(nums.begin(),nums.end());        int count=0,num=nums.size(),l,r;        //遍历        for(int i=num-1;i>=2;i--){            l=0,r=i-1;            while(l<r)            {                if(nums[l]+nums[r]>nums[i])                {                    count+=r-l;                    r--;                }                else                    l++;            }        }        return count;    }};
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 用什么 用的拼音 车用 什么用 什么气垫bb好用 用盐水可以祛痘吗 脂肪粒能用针挑吗 用盐怎么去黑头 用白醋 好用app 闭口粉刺用什么护肤品 什么芦荟胶好用 如何用蜂蜜洗脸 怎么用电脑玩手游 用洗面奶长痘痘 去黑头用什么好 祛斑哪个牌子好用 用酒精擦痘痘 哪种考勤机好用 做网站用什么语言 有红血丝用什么护肤品 用什么脸会变白 海竿用什么线好 什么祛痘膏好用 外国人用的聊天软件 用什么洗脸淡斑 长痘可以用盐水洗脸吗 哪种睫毛夹好用 信用卡干嘛用的 什么甩脂机好用 销售软件哪个好用 怎样用bb霜 淡斑用什么好 订酒店用什么app 用什么东西可以去痘痘 用什么洗脸可以去痘痘 用盐洗脸能祛斑吗 linux怎么用 什么祛痘霜好用 脸上起痘痘用什么洗脸 用手机如何开网店