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.
1using System;
2
3public class Solution {
4 public int TriangleNumber(int[] nums) {
5 Array.Sort(nums);
6 int count = 0;
7 for (int i = nums.Length - 1; i >= 2; i--) {
8 int left = 0, right = i - 1;
9 while (left < right) {
10 if (nums[left] + nums[right] > nums[i]) {
11 count += right - left;
12 right--;
13 } else {
14 left++;
15 }
16 }
17 }
18 return count;
19 }
20
21 public static void Main(string[] args) {
22 Solution sol = new Solution();
23 Console.WriteLine(sol.TriangleNumber(new int[] {2, 2, 3, 4}));
24 }
25}
C# follows the same logical steps by sorting the array and using a double-pointer technique to detect valid triangles.
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
This Brute Force C solution uses three nested loops to examine every triplet and checks if they satisfy the triangle inequality condition.