Leetcode 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.
A triplet (i, j, k) can form a triangle if:
nums[i] + nums[j] > nums[k]
nums[i] + nums[k] > nums[j]
nums[j] + nums[k] > nums[i]
nums
might be up to around 10^3 to 10^4).k
(largest side), use two pointers (i
starting from 0 and j
starting from k-1
) to find if nums[i] + nums[j] > nums[k]
. If such a combination is found, all elements between i
and j-1
with j
will also form a valid triangle due to sorting.#include <vector>
#include <algorithm>
class Solution {
public:
int triangleNumber(std::vector<int>& nums) {
std::sort(nums.begin(), nums.end());
int count = 0;
for (int k = nums.size() - 1; k >= 2; --k) {
int i = 0, j = k - 1;
while (i < j) {
if (nums[i] + nums[j] > nums[k]) {
count += j - i;
--j;
} else {
++i;
}
}
}
return count;
}
};
k
, the pointers i
and j
are iterated over the remaining array.Therefore, the total time complexity of this approach is (O(n^2)), which is efficient for typical constraints on input size (n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?