给定三个数组 a[]、b[] 和 c[],由 N 个元素组成,代表N 个三角形的三边。任务是从给定的三角形中找出唯一的三角形的数量。如果三角形的所有边都与其他三角形的所有边的长度匹配,则该三角形是非唯一的。
例子:
Input: a[] = {1, 2}, b[] = {2, 3}, c[] = {3, 5}
Output: 2
The triangles have sides 1, 2, 3 and 2, 3, 5 respectively.
None of them have same sides. Thus both are unique.
Input: a[] = {7, 5, 8, 2, 2}, b[] = {6, 7, 2, 3, 4}, c[] = {5, 6, 9, 4, 3}
Output: 1
Only triangle with sides 8, 2 and 9 is unique.
方法:想法是,对于每个三角形,对它的所有边进行排序,然后将其存储在地图中,如果所有这三个边都已经存在于地图中,则将频率增加 1,否则其频率将为 1。计数最终频率为 1 的地图元素的一部分将是答案。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the number of unique triangles
int UniqueTriangles(int a[], int b[], int c[], int n)
{
vector sides[n];
// Map to store the frequency of triangles
// with same sides
map, int> m;
for (int i = 0; i < n; i++) {
// Push all the sides of the current triangle
sides[i].push_back(a[i]);
sides[i].push_back(b[i]);
sides[i].push_back(c[i]);
// Sort the three sides
sort(sides[i].begin(), sides[i].end());
// Store the frequency of the sides
// of the triangle
m[sides[i]] = m[sides[i]] + 1;
}
map, int>::iterator i;
// To store the count of unique triangles
int count = 0;
for (i = m.begin(); i != m.end(); i++) {
// If current triangle has unique sides
if (i->second == 1)
count++;
}
return count;
}
// Driver code
int main()
{
int a[] = { 7, 5, 8, 2, 2 };
int b[] = { 6, 7, 2, 3, 4 };
int c[] = { 5, 6, 9, 4, 3 };
int n = sizeof(a) / sizeof(int);
cout << UniqueTriangles(a, b, c, n);
return 0;
}
Python3
# Python3 implementation of the approach
from collections import defaultdict
# Function to return the number
# of unique triangles
def UniqueTriangles(a, b, c, n):
sides = [None for i in range(n)]
# Map to store the frequency of
# triangles with same sides
m = defaultdict(lambda:0)
for i in range(0, n):
# Push all the sides of the current triangle
sides[i] = (a[i], b[i], c[i])
# Sort the three sides
sides[i] = tuple(sorted(sides[i]))
# Store the frequency of the sides
# of the triangle
m[sides[i]] += 1
# To store the count of unique triangles
count = 0
for i in m:
# If current triangle has unique sides
if m[i] == 1:
count += 1
return count
# Driver code
if __name__ == "__main__":
a = [7, 5, 8, 2, 2]
b = [6, 7, 2, 3, 4]
c = [5, 6, 9, 4, 3]
n = len(a)
print(UniqueTriangles(a, b, c, n))
# This code is contributed by Rituraj Jain
输出:
1
时间复杂度: O(N * log(N))
辅助空间: O(N)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。