2022-12-23 18:28:17 +08:00
|
|
|
|
/**
|
|
|
|
|
* File: hashing_search.cs
|
|
|
|
|
* Created Time: 2022-12-23
|
|
|
|
|
* Author: haptear (haptear@hotmail.com)
|
|
|
|
|
*/
|
|
|
|
|
|
2023-04-24 04:20:51 +08:00
|
|
|
|
using hello_algo.utils;
|
2022-12-23 15:42:02 +08:00
|
|
|
|
using NUnit.Framework;
|
|
|
|
|
|
2023-02-08 22:18:02 +08:00
|
|
|
|
namespace hello_algo.chapter_searching;
|
|
|
|
|
|
2023-04-23 03:03:12 +08:00
|
|
|
|
public class hashing_search {
|
2023-02-08 22:18:02 +08:00
|
|
|
|
/* 哈希查找(数组) */
|
2023-04-23 03:03:12 +08:00
|
|
|
|
static int hashingSearchArray(Dictionary<int, int> map, int target) {
|
2023-02-08 22:18:02 +08:00
|
|
|
|
// 哈希表的 key: 目标元素,value: 索引
|
|
|
|
|
// 若哈希表中无此 key ,返回 -1
|
|
|
|
|
return map.GetValueOrDefault(target, -1);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/* 哈希查找(链表) */
|
2023-04-23 03:03:12 +08:00
|
|
|
|
static ListNode? hashingSearchLinkedList(Dictionary<int, ListNode> map, int target) {
|
2023-02-08 22:18:02 +08:00
|
|
|
|
|
2023-04-09 04:32:17 +08:00
|
|
|
|
// 哈希表的 key: 目标节点值,value: 节点对象
|
2023-02-08 22:18:02 +08:00
|
|
|
|
// 若哈希表中无此 key ,返回 null
|
|
|
|
|
return map.GetValueOrDefault(target);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[Test]
|
2023-04-23 03:03:12 +08:00
|
|
|
|
public void Test() {
|
2023-02-08 22:18:02 +08:00
|
|
|
|
int target = 3;
|
|
|
|
|
|
2022-12-23 15:42:02 +08:00
|
|
|
|
/* 哈希查找(数组) */
|
2023-02-08 22:18:02 +08:00
|
|
|
|
int[] nums = { 1, 5, 3, 2, 4, 7, 5, 9, 10, 8 };
|
|
|
|
|
// 初始化哈希表
|
|
|
|
|
Dictionary<int, int> map = new();
|
2023-04-23 03:03:12 +08:00
|
|
|
|
for (int i = 0; i < nums.Length; i++) {
|
2023-02-08 22:18:02 +08:00
|
|
|
|
map[nums[i]] = i; // key: 元素,value: 索引
|
2022-12-23 15:42:02 +08:00
|
|
|
|
}
|
2023-02-08 22:18:02 +08:00
|
|
|
|
int index = hashingSearchArray(map, target);
|
|
|
|
|
Console.WriteLine("目标元素 3 的索引 = " + index);
|
2022-12-23 15:42:02 +08:00
|
|
|
|
|
|
|
|
|
/* 哈希查找(链表) */
|
2023-02-08 22:18:02 +08:00
|
|
|
|
ListNode? head = ListNode.ArrToLinkedList(nums);
|
|
|
|
|
// 初始化哈希表
|
|
|
|
|
Dictionary<int, ListNode> map1 = new();
|
2023-04-23 03:03:12 +08:00
|
|
|
|
while (head != null) {
|
2023-04-09 04:32:17 +08:00
|
|
|
|
map1[head.val] = head; // key: 节点值,value: 节点
|
2023-02-08 22:18:02 +08:00
|
|
|
|
head = head.next;
|
2022-12-23 15:42:02 +08:00
|
|
|
|
}
|
2023-02-08 22:18:02 +08:00
|
|
|
|
ListNode? node = hashingSearchLinkedList(map1, target);
|
2023-04-09 04:32:17 +08:00
|
|
|
|
Console.WriteLine("目标节点值 3 的对应节点对象为 " + node);
|
2022-12-23 15:42:02 +08:00
|
|
|
|
}
|
|
|
|
|
}
|