书是人编的,人在算的时候算错了呗
解答:
根据题目描述,35%13应该是余数为9,但是课本中却将35插入到了12所在的链表中?
这其实是因为采用了取模(%)操作,算法中通过%取得的余数才能被用于构成链,如果我们把13改成4的话,35%4=3,这意味着我们把35放在余数为3的链中,而不是余数为1的链中。
那么,我们需要把35放到13 % 35 = 12的链中,具体步骤如下:
将每个数所在的链表示出来
//定义数组的长度 int hashLength = 13; //测试的数字 int[] numbers = {35, 27, 48, 24}; //用一个整数的链表来保存每个数 int[][] hashTable = new int[hashLength][]; //初始化链表数组,每个都是空的数组 for (int i = 0; i < hashLength; i++) { hashTable[i] = new int[0]; } //循环处理每个数字 for (int i = 0; i < numbers.length; i++) { //计算数字对应的链的下标index int index = numbers[i] % hashLength; //将数字保存在对应的链中,这里使用了Java API中List的toArray方法 hashTable[index] = Arrays.copyOf(hashTable[index], hashTable[index].length + 1); hashTable[index][hashTable[index].length - 1] = numbers[i]; }
清空13 % 12 = 1的链中的元素
//清空13 % 12 = 1的链中的元素,因为这样35就可以放到1的链中了 hashTable[1] = new int[0];
将35插入到13 % 35 = 12的链中
//将35插入到13 % 35 = 12的链中 hashTable[12] = Arrays.copyOf(hashTable[12], hashTable[12].length + 1); hashTable[12][hashTable[12].length - 1] = 35;
验证结果
//验证结果 for (int i = 0; i < hashTable.length; i++) { System.out.print("链" + i + ":"); for (int j = 0; j < hashTable[i].length; j++) { System.out.print(" " + hashTable[i][j]); } System.out.println(); }
合并步骤1~4的完整代码:
import java.util.Arrays;
public class Main { public static void main(String[] args) { //定义数组的长度 int hashLength = 13; //测试的数字 int[] numbers = {35, 27, 48, 24}; //用一个整数的链表来保存每个数 int[][] hashTable = new int[hashLength][]; //初始化链表数组,每个都是空的数组 for (int i = 0; i < hashLength; i++) { hashTable[i] = new int[0]; } //循环处理每个数字 for (int i = 0; i < numbers.length; i++) { //计算数字对应的链的下标index int index = numbers[i] % hashLength; //将数字保存在对应的链中,这里使用了Java API中List的toArray方法 hashTable[index] = Arrays.copyOf(hashTable[index], hashTable[index].length + 1); hashTable[index][hashTable[index].length - 1] = numbers[i]; } //清空13 % 12 = 1的链中的元素,因为这样35就可以放到1的链中了 hashTable[1] = new int[0]; //将35插入到13 % 35 = 12的链中 hashTable[12] = Arrays.copyOf(hashTable[12], hashTable[12].length + 1); hashTable[12][hashTable[12].length - 1] = 35; //验证结果 for (int i = 0; i < hashTable.length; i++) { System.out.print("链" + i + ":"); for (int j = 0; j < hashTable[i].length; j++) { System.out.print(" " + hashTable[i][j]); } System.out.println(); } } }
最后,我们得到结果:
链0: 链1: 链2: 27 链3: 链4: 48 链5: 链6: 链7: 链8: 链9: 链10: 链11: 链12: 35
因此,35确实被正确插入到了当前余数为12的链表中。