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].
A:
method 1 : sort and brute force.
class Solution { public: int triangleNumber(vector<int>& nums) { sort(nums.begin(), nums.end()); int res = 0; int n = nums.size(); for(int i = 0;i<n-2; i++){ for(int j = i+1; j<n-1; j++){ for(int k = j+1; k<n; k++){ if(nums[i]+nums[j]>nums[k]){ ++res; }else{ break; } } } } return res; } };
Method 2 : when search the last value, , and find the index that's min than first two, via binary search
Method 3:sort, then when find 2,3 value, use idea like 2sum, to find pairs.
No comments:
Post a Comment