mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-14 09:48:31 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
@@ -10,42 +10,42 @@ import utils.*;
|
||||
import java.util.*;
|
||||
|
||||
public class hashing_search {
|
||||
/* Hash search (array) */
|
||||
/* Hash-based search (array) */
|
||||
static int hashingSearchArray(Map<Integer, Integer> map, int target) {
|
||||
// Hash table's key: target element, value: index
|
||||
// If this key does not exist in the hash table, return -1
|
||||
// Hash table key: target element; value: index
|
||||
// Return -1 if the hash table does not contain this key
|
||||
return map.getOrDefault(target, -1);
|
||||
}
|
||||
|
||||
/* Hash search (linked list) */
|
||||
/* Hash-based search (linked list) */
|
||||
static ListNode hashingSearchLinkedList(Map<Integer, ListNode> map, int target) {
|
||||
// Hash table key: target node value, value: node object
|
||||
// If key is not in hash table, return null
|
||||
// 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 search (array) */
|
||||
/* Hash-based search (array) */
|
||||
int[] nums = { 1, 5, 3, 2, 4, 7, 5, 9, 10, 8 };
|
||||
// Initialize hash table
|
||||
// Initialize the hash table
|
||||
Map<Integer, Integer> map = new HashMap<>();
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
map.put(nums[i], i); // key: element, value: index
|
||||
map.put(nums[i], i); // key: element; value: index
|
||||
}
|
||||
int index = hashingSearchArray(map, target);
|
||||
System.out.println("Index of target element 3 = " + index);
|
||||
|
||||
/* Hash search (linked list) */
|
||||
/* Hash-based search (linked list) */
|
||||
ListNode head = ListNode.arrToLinkedList(nums);
|
||||
// Initialize hash table
|
||||
// Initialize the hash table
|
||||
Map<Integer, ListNode> map1 = new HashMap<>();
|
||||
while (head != null) {
|
||||
map1.put(head.val, head); // key: node value, value: node
|
||||
map1.put(head.val, head); // key: node value; value: node
|
||||
head = head.next;
|
||||
}
|
||||
ListNode node = hashingSearchLinkedList(map1, target);
|
||||
System.out.println("Node object corresponding to target node value 3 is " + node);
|
||||
System.out.println("The node object corresponding to target value 3 is " + node);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user