zoukankan      html  css  js  c++  java
  • 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. };  
  • 相关阅读:
    Duplicate keys detected: '0'. This may cause an update error.
    better-scroll在移动端绑定click事件失效
    vue-awesome-swiper轮播插件的使用方法及问题。
    可运行的js代码
    CSS3表达式calc( )
    webstorm破解教程
    box-decoration-break属性
    shiro自定义密码校验器
    获取select中option被选中的值
    SpringBoot开发验证码功能
  • 原文地址:https://www.cnblogs.com/liangyc/p/8862612.html
Copyright © 2011-2022 走看看