使用雜湊對映解決鎖和金鑰問題
給定一個不同的鎖的列表和另一個金鑰的列表。我們的任務是從給定的列表中找到鎖和金鑰的正確匹配,並在正確時將該金鑰分配給鎖。
在此方法中,我們將遍歷所有鎖並建立一個雜湊對映,然後在雜湊對映中搜索每個鍵。當鍵匹配時,將該鍵標記為有效鍵並分配給鎖。
輸入和輸出
Input: The lists of locks and keys. lock = { ),@,*,^,(,%, !,$,&,#} key = { !, (, #, %, ), ^, &, *, $, @ } Output: After matching Locks and Keys: Locks: ! ( # % ) ^ & * $ @ Keys: ! ( # % ) ^ & * $ @
演算法
lockAndKeyProblem(lock, key, n)
輸入:鎖的列表、金鑰的列表、n。
輸出:找出哪個金鑰對應於哪個鎖。
Begin define hashmap for i in range (0 to n-1), do hashmap[lock[i]] := i //set hashmap for locks done for i in range (0 to n-1), do if key[i] is found in the hashmap, then lock[i] = key[i] done End
示例
#include<iostream> #include<map> using namespace std; void show(char array[], int n) { for(int i = 0; i<n; i++) cout << array[i] << " "; } void lockAndKeyProblem(char lock[], char key[], int n) { map<char, int> hashMap; for(int i = 0; i<n; i++) hashMap[lock[i]] = i; //hash map for locks for(int i = 0; i<n; i++) //for each keys for each lock if(hashMap.find(key[i]) != hashMap.end()) { lock[i] = key[i]; } } int main() { char lock[] = {')','@','*','^','(','%','!','$','&','#'}; char key[] = {'!','(','#','%',')','^','&','*','$','@'}; int n = 10; lockAndKeyProblem(lock, key, n); cout << "After matching Locks and Keys:"<<endl; cout << "Locks: "; show(lock, n); cout << endl; cout << "Keys: "; show(key, n); cout << endl; }
輸出
After matching Locks and Keys: Locks: ! ( # % ) ^ & * $ @ Keys: ! ( # % ) ^ & * $ @
廣告