54 lines
1.4 KiB
C++
54 lines
1.4 KiB
C++
|
/**
|
|||
|
* File: hashing_search.cpp
|
|||
|
* Created Time: 2022-11-25
|
|||
|
* Author: krahets (krahets@163.com)
|
|||
|
*/
|
|||
|
|
|||
|
#include "../utils/common.hpp"
|
|||
|
|
|||
|
/* <20><>ϣ<EFBFBD><CFA3><EFBFBD>ң<EFBFBD><D2A3><EFBFBD><EFBFBD>飩 */
|
|||
|
int hashingSearchArray(unordered_map<int, int> map, int target) {
|
|||
|
// <20><>ϣ<EFBFBD><CFA3><EFBFBD><EFBFBD> key: Ŀ<><C4BF>Ԫ<EFBFBD>أ<EFBFBD>value: <20><><EFBFBD><EFBFBD>
|
|||
|
// <20><><EFBFBD><EFBFBD>ϣ<EFBFBD><CFA3><EFBFBD><EFBFBD><EFBFBD><EFBFBD> key <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> -1
|
|||
|
if (map.find(target) == map.end())
|
|||
|
return -1;
|
|||
|
return map[target];
|
|||
|
}
|
|||
|
|
|||
|
/* <20><>ϣ<EFBFBD><CFA3><EFBFBD>ң<EFBFBD><D2A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
|
|||
|
ListNode *hashingSearchLinkedList(unordered_map<int, ListNode *> map, int target) {
|
|||
|
// <20><>ϣ<EFBFBD><CFA3><EFBFBD><EFBFBD> key: Ŀ<><C4BF><EFBFBD>ڵ<EFBFBD>ֵ<EFBFBD><D6B5>value: <20>ڵ<EFBFBD><DAB5><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
// <20><><EFBFBD><EFBFBD>ϣ<EFBFBD><CFA3><EFBFBD><EFBFBD><EFBFBD><EFBFBD> key <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> nullptr
|
|||
|
if (map.find(target) == map.end())
|
|||
|
return nullptr;
|
|||
|
return map[target];
|
|||
|
}
|
|||
|
|
|||
|
/* Driver Code */
|
|||
|
int main() {
|
|||
|
int target = 3;
|
|||
|
|
|||
|
/* <20><>ϣ<EFBFBD><CFA3><EFBFBD>ң<EFBFBD><D2A3><EFBFBD><EFBFBD>飩 */
|
|||
|
vector<int> nums = {1, 5, 3, 2, 4, 7, 5, 9, 10, 8};
|
|||
|
// <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD>ϣ<EFBFBD><CFA3>
|
|||
|
unordered_map<int, int> map;
|
|||
|
for (int i = 0; i < nums.size(); i++) {
|
|||
|
map[nums[i]] = i; // key: Ԫ<>أ<EFBFBD>value: <20><><EFBFBD><EFBFBD>
|
|||
|
}
|
|||
|
int index = hashingSearchArray(map, target);
|
|||
|
cout << "Ŀ<EFBFBD><EFBFBD>Ԫ<EFBFBD><EFBFBD> 3 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> = " << index << endl;
|
|||
|
|
|||
|
/* <20><>ϣ<EFBFBD><CFA3><EFBFBD>ң<EFBFBD><D2A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
|
|||
|
ListNode *head = vecToLinkedList(nums);
|
|||
|
// <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD>ϣ<EFBFBD><CFA3>
|
|||
|
unordered_map<int, ListNode *> map1;
|
|||
|
while (head != nullptr) {
|
|||
|
map1[head->val] = head; // key: <20>ڵ<EFBFBD>ֵ<EFBFBD><D6B5>value: <20>ڵ<EFBFBD>
|
|||
|
head = head->next;
|
|||
|
}
|
|||
|
ListNode *node = hashingSearchLinkedList(map1, target);
|
|||
|
cout << "Ŀ<EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD>ֵ 3 <20>Ķ<EFBFBD>Ӧ<EFBFBD>ڵ<EFBFBD><DAB5><EFBFBD><EFBFBD><EFBFBD>Ϊ " << node << endl;
|
|||
|
|
|||
|
return 0;
|
|||
|
}
|