Sponsored
Sponsored
First, sort the array. Then, iterate through the array by selecting the third side of the triplet. Use a two-pointer technique to find valid pairs for the first and second sides. For each third side, initialize two pointers, one starting at the beginning of the list and the other just before the third side. Check the sum of the elements at the two pointers and compare it to the third side. If they form a valid triangle, move the inner pointer inward; otherwise, adjust the pointers accordingly.
Time Complexity: O(n^2), where n is the length of the input array because the main operations involve sorting and a nested loop.
Space Complexity: O(1) since it uses only a fixed amount of extra space.
1#include <stdio.h>
2#include <stdlib.h>
3
4int compare(const void *a, const void *b) {
5 return *(int *)a - *(int *)b;
6}
7
8int triangleNumber(int* nums, int numsSize) {
9 if (numsSize < 3) return 0;
10 qsort(nums, numsSize, sizeof(int), compare);
11 int count = 0;
12 for (int i = numsSize - 1; i >= 2; i--) {
13 int left = 0, right = i - 1;
14 while (left < right) {
15 if (nums[left] + nums[right] > nums[i]) {
16 count += right - left;
17 right--;
18 } else {
19 left++;
20 }
21 }
22 }
23 return count;
24}
25
26int main() {
27 int nums[] = {2, 2, 3, 4};
28 int size = sizeof(nums) / sizeof(nums[0]);
29 printf("%d\n", triangleNumber(nums, size));
30 return 0;
31}
This solution sorts the array and uses nested loops; the outer loop selects the third side, and the inner loop uses two pointers to find valid pairs for the other two sides. By moving the pointers towards each other based on the condition, it efficiently finds all valid triplets.
This approach involves checking every possible triplet from the array to see if they can form a triangle by comparing their sums directly. This solution is straightforward but less efficient since it considers all combinations without optimizations such as sorting or double pointers.
Time Complexity: O(n^3), as it checks every combination of three numbers in the array.
Space Complexity: O(1), requiring minimal additional storage.
1
The Python implementation relies on three nested loops to test all combinations, ensuring each qualifies the triangle inequality condition for valid triplets.