[LeetCode] Valid Triangle Number

611. Valid Triangle Number

Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int triangleNumber(vector<int>& nums) {
sort(nums.begin(), nums.end());
int res = 0;
for(int i = 0; i < nums.size(); i++) {
for(int j = i + 1; j < nums.size(); j++) {
auto bound = prev(lower_bound(nums.begin() + j + 1, nums.end(), nums[i] + nums[j]));
auto dis = bound - (nums.begin() + j);
if(dis > 0) {
res += dis;
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/25/PS/LeetCode/valid-triangle-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.