题目
给你一个下标从 0 开始的整数数组
arr
和一个m x n
的整数 矩阵mat
。arr
和mat
都包含范围[1,m * n]
内的 所有 整数。从下标
0
开始遍历arr
中的每个下标i
,并将包含整数arr[i]
的mat
单元格涂色。请你找出
arr
中在mat
的某一行或某一列上都被涂色且下标最小的元素,并返回其下标i
。
解题思路
- 先将元素和位置通过map进行绑定,便于后续查找;
- 通过双层for循环来寻找最早填充行的位置和最早填充列的位置;
- 同一行或同一列内以最晚填充的为准,不同行不同列以最早填充为准。
代码展示
class Solution { public int firstCompleteIndex(int[] arr, int[][] mat) { int size = arr.length; Map<Integer,Integer> data = new HashMap<>(); for (int i = 0; i < size; i++){ data.put(arr[i], i); } int min = Integer.MAX_VALUE; //求行最小 for (int i = 0; i < mat.length; i++){ int max = Integer.MIN_VALUE; for (int j = 0; j < mat[0].length; j++){ max = Math.max(max, data.get(mat[i][j])); } min = Math.min(min, max); } //求列最小 for (int i = 0; i < mat[0].length; i++){ int max = Integer.MIN_VALUE; for (int j = 0; j < mat.length; j++){ max = Math.max(max, data.get(mat[j][i])); } min = Math.min(min, max); } return min; } }