-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path611_Valid_Triangle_Number.cpp
More file actions
39 lines (35 loc) · 1008 Bytes
/
611_Valid_Triangle_Number.cpp
File metadata and controls
39 lines (35 loc) · 1008 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
int triangleNumber(vector<int>& nums) {
int n = nums.size();
// T.C: O(n^3) , S.C : O(1)
// int cnt = 0;
// sort(nums.begin(), nums.end());
// 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]){
// cnt++;
// }
// }
// }
// }
// return cnt;
// T.C = O(n^2) S.C: O(1)
int cnt = 0;
sort(nums.begin(), nums.end());
for(int k = n-1; k>=2; k--){
int i = 0, j = k-1;
while(i<j){
if(nums[i]+nums[j]>nums[k]){
cnt += (j-i);
j--;
}
else{
i++;
}
}
}
return cnt;
}
};