本文介绍: 的某一行或某一列上都被涂色且下标最小元素,并返回下标

题目

给你一个下标从 0 开始的整数数组 arr 和一个 m x n 的整数 矩阵 mat 。arr 和 mat 都包含范围 [1,m * n] 内的 所有 整数

下标 0 开始遍历 arr 中的每个下标 i ,并将包含整数 arr[i] 的 mat 单元格涂色。

请你找出 arr 中在 mat 的某一行或某一列上都被涂色且下标最小的元素,并返回其下标 i 。

解题思路

  1. 先将元素和位置通过map进行绑定,便于后续查找
  2. 通过双层for循环来寻找最早填充行的位置和最早填充列的位置
  3. 同一行或同一列内以最晚填充的为准,不同不同列以最早填充为准。

代码展示

class Solution {
    public int firstCompleteIndex(int[] arr, int[][] mat) {
        int size = arr.length;
        Map&lt;Integer,Integer&gt; data = new HashMap<&gt;();
        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;
    }
}

原文地址:https://blog.csdn.net/qq_45794129/article/details/134727119

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_32442.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注