在 C++ 中使用陣列的位陣列查詢重複項
概念
我們有一個由 n 個數字組成的陣列,其中 n 的最大值為 32,000。現在給定的陣列可能包含重複的條目,但我們不知道 n 是多少。現在提出的問題是,在只有 4 千位元組可用記憶體的情況下,如何在陣列中顯示或打印出所有重複的元素?
輸入
arr[] = {2, 6, 2, 11, 13, 11}輸出
2 11 2 and 11 appear more than once in given array.
輸入
arr[] = {60, 50, 60}輸出
60
方法
現在我們有 4 千位元組的記憶體,這表示我們可以定址最多 8 * 4 * 210 位元。需要注意的是,32 * 210 位元大於 32000。因此,我們可以生成一個由 32000 位元組成的點陣圖,其中每個位元代表一個整數。
同樣需要注意的是,如果我們需要生成一個位元數大於 32000 的點陣圖,那麼我們可以輕鬆地生成 32000 以上的位元數;透過實現這個位向量,我們能夠遍歷陣列,透過將每個元素 v 設定為 1 來標記它。在這種情況下,當我們遍歷重複元素時,我們列印它。
示例
// C++ program to print all Duplicates in array
#include <bits/stdc++.h>
using namespace std;
// Shows a class to represent an array of bits using
// array of integers
class BitArray{
int *arr1;
public:
BitArray() {}
// Constructor
BitArray(int n1){
// Used to divide by 32. To store n bits, we require
// n/32 + 1 integers (Assuming int is stored
// using 32 bits)
arr1 = new int[(n1 >> 5) + 1];
}
// Now get value of a bit at given position
bool get(int pos1){
// Used to divide by 32 to find position of
// integer.
int index1 = (pos1 >> 5);
// Now determine bit number in arr[index]
int bitNo1 = (pos1 & 0x1F);
// Determine value of given bit number in
// arr1[index1]
return (arr1[index1] & (1 << bitNo1)) != 0;
}
// Used to set a bit at given position
void set(int pos1){
// Determine index of bit position
int index1 = (pos1 >> 5);
// Used to set bit number in arr1[index1]
int bitNo1 = (pos1 & 0x1F);
arr1[index1] |= (1 << bitNo1);
}
//Shows main function to print all Duplicates
void checkDuplicates1(int arr1[], int n1){
// Used to create a bit with 32000 bits
BitArray ba1 = BitArray(320000);
// Used to traverse array elements
for (int i = 0; i < n1; i++){
// Shows index in bit array
int num1 = arr1[i];
// Now if num is already present in bit array
if (ba1.get(num1))
cout << num1 << " ";
// Otherwise or else insert num
else
ba1.set(num1);
}
}
};
// Driver code
int main(){
int arr1[] = {2, 6, 2, 11, 13, 11};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
BitArray obj1 = BitArray();
obj1.checkDuplicates1(arr1, n1);
return 0;
}輸出
2 11
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP