Hash Table Implementation
Full code:
#include <iostream>using namespace std;enum status{empty,exit};int _hash (int num, int n, int* hashtable, int* status) {Int index = num % n;if (Status[index] == empty) {//The current position does not map any number status[index] = exit;} else if (Status[index] == exit&&hashtable[index] == num) {// The current position has mapped numbers and is equal to the number that will be mapped;} else{//the current position has mapped numbers but not the number to be mapped, two probes are needed to find the correct subscript for the number to be mapped int i = 1;while (status[index] == exit) && (hashtable[index] != num)) {index += (2 * i &NBSP;+&NBSP;1);//hash of the two-time probe}status[index] = exit;} Return index;} Int solution (int* arr, int n) {if (arr == null | | n <= 0) return 0;int* hashtable = new int[n];int* status = new int[n];int* count = new int[n];memsET (hashtable, 0, n*sizeof (int));for (int i = 0; i < n; ++ i) Status[i] = empty;memset (count, 0, n*sizeof (int));for (int i = 0; i < n; ++i) {Int index = _hash (arr[i], n, hashtable,status); Hashtable[index] = arr[i];++count[index];} /*for (int i = 0; i<n; ++i) {cout << hashtable[i] < < " ";} cout << endl;for (int i = 0; i<n; ++i) {cout << count[i] << " ";} cout << endl;*///Find the second most occurrences of the number in the Hashtable subscript int max1 = count[0], max2 = count[1];//input data should be legal, otherwise it will crash int min;for (int i = 2; i < n; ++i) {Int f = max1, s = max2, t = count[i];max1 = f>s ? f&nBsp;: s; min = f>s ? s : f;max2 = min > t ? min : t;} Int index = max1 > max2 ? max2 : max1;int i = 0 ;int max = -1;while (Count[i] != index) {++i;} Max = hashtable[i];d elete[] hashtable;delete[] status;delete[] count;return 0;} Int main () {int arr[] = { 0, 14, 5, 8, 0, 14, 35, 36, 87, 0, 10, 10, 10, 10, 10, 5, 5, 6 };cout<< Solution (Arr, sizeof (arr)/sizeof (arr[0]) <<endl;system ("Pause");}
This article from "Zero Egg" blog, declined reprint!
The number of occurrences of the second number in the array--hash table