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. };  
  • 相关阅读:
    Command 命令模式
    Composite 组合模式
    Decorator 装饰器模式
    Abstract Factory 抽象工厂模式
    输入框测试重点:
    w​e​b​网​站​常​用​测​试​用​例
    性能测试常见分类
    Web 常用的测试方法
    em、rem和px的区别
    [if lt IE 9]等符号的含义
  • 原文地址:https://www.cnblogs.com/liangyc/p/8862612.html
Copyright © 2011-2022 走看看