Leetcode 2661. 找出叠涂元素

  • Leetcode 2661. 找出叠涂元素
  • 题目
    • 给你一个下标从 0 开始的整数数组 arr 和一个 m x n 的整数 矩阵 mat 。arr 和 mat 都包含范围 [1,m * n] 内的 所有 整数。
    • 从下标 0 开始遍历 arr 中的每个下标 i ,并将包含整数 arr[i] 的 mat 单元格涂色。
    • 请你找出 arr 中在 mat 的某一行或某一列上都被涂色且下标最小的元素,并返回其下标 i 。
    • m == mat.length
    • n = mat[i].length
    • arr.length == m * n
    • 1 <= m, n <= 10 ^ 5
    • 1 <= m * n <= 10 ^ 5
    • 1 <= arr[i], mat[r][c] <= m * n
    • arr 中的所有整数 互不相同
    • mat 中的所有整数 互不相同
  • 解法
    • 将 mat 每个数对应的行列号放入 HashMap,然后遍历 arr 数字,找到每个行列号对应加 1,当某个行号的数字加到 n(总列数)、或者列号的数字加到 m(总行数)就是结果
    • 时间复杂度:O(mn),空间复杂地:O(mn)
  • 代码
/**
     * 将 mat 每个数对应的行列号放入 HashMap,然后遍历 arr 数字,找到每个行列号对应加 1,当某个行号的数字加到 n(总列数)、或者列号的数字加到 m(总行数)就是结果
     */
    public int solution(int[] arr, int[][] mat) {
        // 判空
        if(arr == null || mat == null || mat.length <= 0) {
            return -1;
        }

        int m = mat.length;
        int n = mat[0].length;

        // 将 mat 每个数对应的行列号放入 HashMap
        Map<Integer, Pair<Integer, Integer>> matRowColMap = new HashMap<>();

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                matRowColMap.put(mat[i][j], new Pair<>(i, j));
            }
        }

        int res = -1;
        int[] rowCount = new int[m];
        int[] colCount = new int[n];
        // 遍历 arr 数字,找到每个行列号对应加 1
        for (int i = 0; i < m * n; i++) {
            Pair<Integer, Integer> rowColPair = matRowColMap.get(arr[i]);

            rowCount[rowColPair.getKey()]++;
            colCount[rowColPair.getValue()]++;

            if (rowCount[rowColPair.getKey()] == n || colCount[rowColPair.getValue()] == m) {
                res = i;
                break;
            }
        }

        return res;

    }

你可能感兴趣的:(LeetCode,leetcode,算法)