2023-01-06 03:39:19 +08:00
|
|
|
|
/**
|
2022-11-25 02:04:38 +08:00
|
|
|
|
* File: hashing_search.java
|
|
|
|
|
* Created Time: 2022-11-25
|
|
|
|
|
* Author: Krahets (krahets@163.com)
|
|
|
|
|
*/
|
|
|
|
|
|
2022-11-20 02:03:26 +08:00
|
|
|
|
package chapter_searching;
|
|
|
|
|
|
2023-04-24 04:11:18 +08:00
|
|
|
|
import utils.*;
|
2022-11-20 02:03:26 +08:00
|
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
|
|
public class hashing_search {
|
|
|
|
|
/* 哈希查找(数组) */
|
2023-02-04 23:49:37 +08:00
|
|
|
|
static int hashingSearchArray(Map<Integer, Integer> map, int target) {
|
2022-11-20 02:03:26 +08:00
|
|
|
|
// 哈希表的 key: 目标元素,value: 索引
|
|
|
|
|
// 若哈希表中无此 key ,返回 -1
|
|
|
|
|
return map.getOrDefault(target, -1);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/* 哈希查找(链表) */
|
2023-02-04 23:49:37 +08:00
|
|
|
|
static ListNode hashingSearchLinkedList(Map<Integer, ListNode> map, int target) {
|
2023-04-09 04:32:17 +08:00
|
|
|
|
// 哈希表的 key: 目标节点值,value: 节点对象
|
2022-11-27 04:20:30 +08:00
|
|
|
|
// 若哈希表中无此 key ,返回 null
|
2022-11-20 02:03:26 +08:00
|
|
|
|
return map.getOrDefault(target, null);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
int target = 3;
|
|
|
|
|
|
|
|
|
|
/* 哈希查找(数组) */
|
|
|
|
|
int[] nums = { 1, 5, 3, 2, 4, 7, 5, 9, 10, 8 };
|
|
|
|
|
// 初始化哈希表
|
|
|
|
|
Map<Integer, Integer> map = new HashMap<>();
|
|
|
|
|
for (int i = 0; i < nums.length; i++) {
|
2023-04-14 00:12:10 +08:00
|
|
|
|
map.put(nums[i], i); // key: 元素,value: 索引
|
2022-11-20 02:03:26 +08:00
|
|
|
|
}
|
2023-02-04 23:49:37 +08:00
|
|
|
|
int index = hashingSearchArray(map, target);
|
2022-11-20 02:03:26 +08:00
|
|
|
|
System.out.println("目标元素 3 的索引 = " + index);
|
|
|
|
|
|
|
|
|
|
/* 哈希查找(链表) */
|
|
|
|
|
ListNode head = ListNode.arrToLinkedList(nums);
|
|
|
|
|
// 初始化哈希表
|
|
|
|
|
Map<Integer, ListNode> map1 = new HashMap<>();
|
|
|
|
|
while (head != null) {
|
2023-04-14 00:12:10 +08:00
|
|
|
|
map1.put(head.val, head); // key: 节点值,value: 节点
|
2022-11-20 02:03:26 +08:00
|
|
|
|
head = head.next;
|
|
|
|
|
}
|
2023-02-04 23:49:37 +08:00
|
|
|
|
ListNode node = hashingSearchLinkedList(map1, target);
|
2023-04-09 04:32:17 +08:00
|
|
|
|
System.out.println("目标节点值 3 的对应节点对象为 " + node);
|
2022-11-20 02:03:26 +08:00
|
|
|
|
}
|
|
|
|
|
}
|