数组hash
前言
数组hash赋能,能快速搜索自己存起的数据,数组hash为基本数据类型,在运行时间上也会快一些。
一、有效的数独
二、二维三维数组hash
package com.xhu.offer.top100;
//有效的数独
public class IsValidSudoku {
//用数组hash记录,空间换时间。
//行hash,列hash,九宫格hash。
public boolean isValidSudoku(char[][] board) {
int[][] row = new int[9][9];
int[][] col = new int[9][9];
int[][][] grid = new int[3][3][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char idx = board[i][j];
if ('.' == idx) continue;
int index = idx - '0' - 1;
int r = i / 3, c = j / 3;
//看行、看列、看九宫格
if (1 == row[i][index] || 1 == col[j][index] || 1 == grid[r][c][index]) return false;
row[i][index] = 1;
col[j][index] = 1;
grid[r][c][index] = 1;
}
}
return true;
}
}
总结
1)hash数组可以以O(1)的时间搜索和删除。
参考文献
[1] LeetCode 有效的数独