使用 C++ 计算给定元素集合中矩形和正方形的可能数量
在这个问题中,我们给定一个包含 N 个整数的数组,表示 n 根木棍的长度。我们的任务是打印可以使用这些木棍创建的矩形和正方形的数量。
让我们来看一个例子来理解这个问题
输入 − array = {5, 5, 7, 7, 1, 4}
输出 − 1
解释 − 一个边长为 5、5、7、7 的矩形。
为了解决这个问题,我们将不得不检查是否可以创建矩形和正方形。
现在,要创建一个正方形或矩形,应该有两根相同长度的木棍,矩形需要2根,正方形需要4根。现在,在我们的数组中,我们将不得不检查相同长度木棍的对数。为了方便搜索,我们将对数组进行排序,然后找到对数,总对数的一半将是可创建的正方形或矩形的数量。
示例
程序展示了我们解决方案的实现,
#include <bits/stdc++.h>
using namespace std;
int countRecSqr(int sticks[], int n) {
sort(sticks, sticks + n);
int pairs = 0;
for (int i = 0; i < n - 1; i++) {
if (sticks[i]==sticks[i + 1]) {
pairs++;
i++;
}
}
return pairs / 2;
}
int main() {
int sticks[] = { 2, 2, 4, 4, 4, 4, 6, 6, 6, 7, 7, 9, 9 };
int n = sizeof(sticks) / sizeof(sticks[0]);
cout<<"The total number of squares or rectangles that can be created is ";
cout<<countRecSqr(sticks, n);
return 0;
}输出
The total number of squares or rectangles that can be created is 3
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP