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:
- The length of the given array won't exceed 1000.
- The integers in the given array are in the range of [0, 1000].
解题思路:
别用深搜n3。确定2个数字实际上在n的时间可以解决,所以可以用n^2来解决这个问题。
- class Solution {
- public:
- int triangleNumber(vector<int>& nums) {
- if(nums.size()<3)return 0;
- sort(nums.begin(),nums.end());
- int max_index=nums.size()-1;
- int temp;
- int count=0;
- int now_second;
- int now_first;
- for(int i=max_index;i>=2;i--){
- now_second = i-1;
- now_first = 0;
- while(now_first<now_second){
- for(int j=now_first;j<now_second;j++){
- if(nums[j]+nums[now_second]>nums[i]){now_first = j;count+=(now_second-now_first);break;}
- }
- now_second--;
- }
- }
- return count;
- }
- };