赞
踩
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.
Input: nums = [2,2,3,4]
Output: 3
Explanation: Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3
Input: nums = [4,2,3,4]
Output: 4
From: LeetCode
Link: 611. Valid Triangle Number
1. Sorting: The array is sorted using qsort which is a standard library function in C for quicksort.
2. Three Pointers: Using a similar strategy as in Python:
3. Counting Triangles: For each valid configuration where the sum of two smaller sides is greater than the third side, count all possible valid combinations between left and right.
// Helper function to compare integers for qsort int intCompare(const void* a, const void* b) { return (*(int*)a - *(int*)b); } // Function to count valid triangle triplets int triangleNumber(int* nums, int numsSize) { qsort(nums, numsSize, sizeof(int), intCompare); // Sort the array int count = 0; for (int i = 2; i < numsSize; i++) { int left = 0, right = i - 1; while (left < right) { if (nums[left] + nums[right] > nums[i]) { count += (right - left); // All pairs from left to right-1 with current right are valid right--; } else { left++; } } } return count; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。