这是散列解决方案的快速伪代码,因此您可以了解其背后的“概念”。我会尝试将其设为 C,但不要假设它已经过编译和测试。但它会很接近。
#include <iostream>
using namespace std;
const int NUM_BITS = 32;
bool noDuplicates(const int INPUT[], const int SIZE, const int MIN_VALUE, const int MAX_VALUE) {
const unsigned int RANGE = (MAX_VALUE - MIN_VALUE) / NUM_BITS; //Use unsigned int, can support wider ranges this way.
int isPresent[RANGE];// Might need dynamic allocation here, don't know if C supports this type of array initialization
for(int i = 0; i < RANGE; i++) isPresent[i] = 0;//Probably don't need this loop on most systems. Aslo, there are faster ways to zero memory.
for(int i = 0; i < SIZE; i++) {
const int ADJUST_TO_ZERO = INPUT[i] - MIN_VALUE; //adjust our min value to zero index now every possible value should map to an indice in our "isPresent" array
const int INT_IN_ARRAY = ADJUST_TO_ZERO / NUM_BITS; // Each int represents 32 values, or our bit is hiding in the (VALUE/32)th slot
const unsigned int BIT_VALUE = 1 << (ADJUST_TO_ZERO % NUM_BITS); // This is identical to 2 ^ (ADJUST_TO_ZERO % NUM_BITS)
cout << "CHECKING: " << ADJUST_TO_ZERO << " ARRAY INDEX: " << INT_IN_ARRAY << " BIT:" << (ADJUST_TO_ZERO % NUM_BITS) << " INT REPRESENTATION: " << BIT_VALUE << endl;
if(isPresent[INT_IN_ARRAY] & BIT_VALUE) { //bitwise &, with a value 2 ^ BIT, isolates this "BIT"
return false;
}
isPresent[ADJUST_TO_ZERO / NUM_BITS] += BIT_VALUE; //If we add 2^BIT to an int, we are only adding the value to this to set this "BIT"
}
return true; //If we escape the loop above there are no duplicates
}
int main() {
const int SIZE = 65;
int array[SIZE];
for(int i = 0; i < SIZE; i++) {
array[i] = i;
}
array[SIZE - 1] = 30;
cout << "RESULT: " << noDuplicates(array, SIZE, 0, 100) << endl;
}