使用哈希映射解决锁和密钥问题
给定一个不同的锁的列表和另一个密钥的列表。我们的任务是从给定的列表中找到锁和密钥的正确匹配,并在正确时将该密钥分配给锁。
在此方法中,我们将遍历所有锁并创建一个哈希映射,然后在哈希映射中搜索每个键。当键匹配时,将该键标记为有效键并分配给锁。
输入和输出
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
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
#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: ! ( # % ) ^ & * $ @
广告