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

    解题思路:

    别用深搜n3。确定2个数字实际上在n的时间可以解决,所以可以用n^2来解决这个问题。

    1. class Solution {  
    2. public:  
    3.     int triangleNumber(vector<int>& nums) {  
    4.         if(nums.size()<3)return 0;  
    5.         sort(nums.begin(),nums.end());  
    6.           
    7.         int max_index=nums.size()-1;  
    8.         int temp;  
    9.         int count=0;  
    10.         int now_second;  
    11.         int now_first;  
    12.         for(int i=max_index;i>=2;i--){  
    13.               
    14.             now_second = i-1;  
    15.             now_first = 0;  
    16.             while(now_first<now_second){  
    17.             for(int j=now_first;j<now_second;j++){  
    18.                 if(nums[j]+nums[now_second]>nums[i]){now_first = j;count+=(now_second-now_first);break;}  
    19.             }  
    20.             now_second--;  
    21.             }  
    22.             }  
    23.             return count;   
    24.     }  
    25. };  
  • 相关阅读:
    我的图片爬虫demo
    修改django后台用户名和密码
    mybatis知识点(已掌握)
    python3与python2的区别(目前遇到的)
    Linux 日常命令
    手机号码归属地查询api接口
    Install-Package EntityFramework -version 5.0.0.0
    【迁移】—Entity Framework实例详解
    Android Http请求方法汇总
    Android数据存储的5种方法
  • 原文地址:https://www.cnblogs.com/liangyc/p/8862612.html
Copyright © 2020-2023  润新知