给出了不同锁的列表和其他键的列表。我们的任务是从给定的列表中找到锁和钥匙的正确匹配,并在正确时为该钥匙分配锁。
在这种方法中,我们将遍历所有锁并创建一个哈希表,然后在哈希表中搜索每个键。如果钥匙匹配,则将其标记为有效钥匙并分配一个锁。
Input: The lists of locks and keys. lock = { ),@,*,^,(,%, !,$,&,#} key = { !, (, #, %, ), ^, &, *, $, @ } Output: 匹配锁和钥匙后: 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 << "匹配锁和钥匙后:"<<endl; cout << "Locks: "; show(lock, n); cout << endl; cout << "Keys: "; show(key, n); cout << endl; }
输出结果
匹配锁和钥匙后: Locks: ! ( # % ) ^ & * $ @ Keys: ! ( # % ) ^ & * $ @