74 使用BitSet输出数组中的重复元素
【本文链接】
http://www.cnblogs.com/hellogiser/p/using-bitset-to-print-duplicate-elements-of-array.html
【题目】
一个数组有L个元素,取值范围为0到N,其中N<32000,但是不知道N的确切大小。L个元素中有若干个重复元素,只有4KB的内存,如何输出重复元素?
【分析】
由于数组的取值在一个范围range[1,32000)之间,我们很自然想到用Bitset来处理。使用Bitset,那么1个整数可以使用1个Bit来表示。1byte能够表示8个不同的整数,4kb能够表示32kb个不同整数。因为32kb=32*1024>32000,那么4kb的内存足够表示32000个不同数字。核心在于Bitset中1个整数的存取。开辟一个能够存储N/32+1个int数字的数组,那么对于数字x存储在array[x/32]这个整数的第x%32个bit位。
即令i=x/32,j=x%32, array[i] |= (1<<j)
等价于i=x>>5,j=x&(0x1F)
【代码】
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
// 74_Bitset.cpp : Defines the entry point for the console application.
// #include "stdafx.h" #include "iostream" #include <ctime> #include <algorithm> using namespace std; class BitSet { public: BitSet (int range) { // [0,range) m_nRange = range; m_nLength = m_nRange / 32 + 1; bitset = new int[m_nLength]; // init all with 0 for (int i = 0; i < m_nLength; i++) { bitset[i] = 0; } } ~BitSet() { delete []bitset; } void Set(int number) { int i = number / 32; int j = number % 32; bitset[i] |= (1 << j); } bool Get(int number) { int i = number / 32; int j = number % 32; return (bitset[i] & (1 << j)) != 0; } void Output() { for (int i = 0; i < m_nRange; i++) { if (Get(i)) { cout << i << " "; } } cout << endl; } private: int *bitset; int m_nRange; // range of numbers int m_nLength; // len of array }; void print(int *a, int n) { for (int i = 0; i < n; i++) { cout << a[i] << " "; } cout << endl; } void PrintDuplicateNumbers(int *a, int n, int count) { cout << "Array numbers======================\n"; print(a, n); cout << "Duplicate numbers======================\n"; BitSet bs(count); for (int i = 0; i < n; i++) { if (bs.Get(a[i])) cout << a[i] << " "; else bs.Set(a[i]); } cout << endl; cout << "Existing numbers======================\n"; bs.Output(); } void test_defualt() { const int n = 20; const int range = 12; srand((unsigned int)time(NULL)); int a[n]; for (int i = 0; i < n; i++) { a[i] = rand() % range; } PrintDuplicateNumbers(a, n, range); } int _tmain(int argc, _TCHAR *argv[]) { test_defualt(); return 0; } /* Array numbers====================== 7 0 2 8 0 3 0 3 2 1 7 5 11 5 4 11 1 0 2 4 Duplicate numbers====================== 0 0 3 2 7 5 11 1 0 2 4 Existing numbers====================== 0 1 2 3 4 5 7 8 11 */ |
【本文链接】
http://www.cnblogs.com/hellogiser/p/using-bitset-to-print-duplicate-elements-of-array.html