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. };  

猜你喜欢

转载自www.cnblogs.com/liangyc/p/8862612.html