public static boolean checkDuplicateWithinK(int[][] mat, int k){ class Cell{ int row; int col; public Cell(int r, int c){ this.row = r; this.col = c; } } int n = mat.length; int m = mat[0].length; k = Math.min(k, n*m); //map from distance to cell postions of the matrix Map > map = new HashMap >(); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(map.containsKey(mat[i][j])){ for(Cell c : map.get(mat[i][j])){ int Dist = Math.abs(i - c.row)+Math.abs(j - c.col); if(Dist <= k){ return true; } if(i - c.row > k){ map.remove(c); } } map.get(mat[i][j]).add(new Cell(i, j)); } else{ map.put(mat[i][j], new HashSet ()); map.get(mat[i][j]).add(new Cell(i, j)); } } } return false;} |
public boolean checkDuplicatesWithinK(int[][] matrix, int k) { //convert matrix to an array int[] arr = Arrays.stream(matrix) .flatMapToInt(Arrays::stream) .toArray(); // Creates an empty hashset HashSet set = new HashSet<>(); // Traverse the input array for (int i = 0; i < arr.length; i++) { // If already present n hash, then we found // a duplicate within k distance if (set.contains(arr[i])) return true; // Add this item to hashset set.add(arr[i]); // Remove the k+1 distant item if (i >= k) set.remove(arr[i - k]); } return false; }