使用 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