/** * File: hashing_search.java * Created Time: 2022-11-25 * Author: krahets (krahets@163.com) */ package chapter_searching; import utils.*; import java.util.*; public class hashing_search { /* Hash-based search (array) */ static int hashingSearchArray(Map map, int target) { // Hash table key: target element; value: index // Return -1 if the hash table does not contain this key return map.getOrDefault(target, -1); } /* Hash-based search (linked list) */ static ListNode hashingSearchLinkedList(Map map, int target) { // Hash table key: target node value; value: node object // Return null if the hash table does not contain this key return map.getOrDefault(target, null); } public static void main(String[] args) { int target = 3; /* Hash-based search (array) */ int[] nums = { 1, 5, 3, 2, 4, 7, 5, 9, 10, 8 }; // Initialize the hash table Map map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); // key: element; value: index } int index = hashingSearchArray(map, target); System.out.println("Index of target element 3 = " + index); /* Hash-based search (linked list) */ ListNode head = ListNode.arrToLinkedList(nums); // Initialize the hash table Map map1 = new HashMap<>(); while (head != null) { map1.put(head.val, head); // key: node value; value: node head = head.next; } ListNode node = hashingSearchLinkedList(map1, target); System.out.println("The node object corresponding to target value 3 is " + node); } }