使用雜湊對映的鎖和鑰匙問題
給定了一個不同鎖的列表和另一個金鑰的列表。我們的任務是從給定的列表中找到鎖和金鑰的正確匹配,並在正確時將該金鑰分配給鎖。
在這種方法中,我們將遍歷所有鎖並建立一個雜湊對映,之後,在雜湊對映中搜索每個金鑰。當金鑰匹配時,則將其標記為有效金鑰並分配給鎖。
輸入和輸出
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: ! ( # % ) ^ & * $ @
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP