| June 2014 |
|
August 2014 | |||||||||||||||||||||||||||||||||||||||||||||||||
struct Hash {
int key;
int value;
Hash(int k, int v) { key = k; value = v; }
int getKey() { return key; }
int getValue() { return value; }
};
//Hash Map class implementation
const int TABLE_SIZE = 128;
class HashMap {
private:
Hash **table;
public:
HashMap() {
table = new Hash*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; ++i) {
table[i] = NULL;
}
}
int get(int key) {
int hash = (key % TABLE_SIZE);
while (table[hash] != NULL && table[hash]->getKey() != key) {
hash = (hash + 1) % TABLE_SIZE;
}
if (table[hash] == NULL) return -1;
return table[hash]->getValue();
}
void put(int key, int value) {
int hash = (key % TABLE_SIZE);
while (table[hash] != NULL && table[hash]->getKey() != key) {
hash = (hash + 1) % TABLE_SIZE;
}
if (table[hash] != NULL) delete table[hash];
table[hash] = new Hash(key, value);
}
~HashMap() {
for (int i = 0; i < TABLE_SIZE; ++i) {
if (table[i] != NULL) delete table[i];
}
delete[] table;
}
};
Turns out the answer is simple but it takes a while to recognize the pattern.
Let Nk be the number of ways to climb k stairs taking only 1 or 2 steps.
We know that N1 = 1 and N2 = 2. Now, consider Nk for
k ≥ 3. The first step will be of size 1 or 2. In the first case there are Nk−1
ways to finish. In the second case there areNk−2
ways to finish. Thus
Nk = Nk−1 + Nk−2
This is Fibonacci sequence!