[路飞]_leetcode 1380. 矩阵中的幸运数

451 阅读2分钟

「这是我参与2022首次更文挑战的第28,活动详情查看:2022首次更文挑战

1380. 矩阵中的幸运数

给你一个 m * n 的矩阵,矩阵中的数字 各不相同 。请你按 任意 顺序返回矩阵中的所有幸运数。

幸运数是指矩阵中满足同时下列两个条件的元素:

在同一行的所有元素中最小 在同一列的所有元素中最大  

示例 1:

输入:matrix = [[3,7,8],[9,11,13],[15,16,17]]
输出:[15]
解释:15 是唯一的幸运数,因为它是其所在行中的最小值,也是所在列中的最大值。

示例 2:

输入:matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]
输出:[12]
解释:12 是唯一的幸运数,因为它是其所在行中的最小值,也是所在列中的最大值。

示例 3:

输入:matrix = [[7,8],[1,2]]
输出:[7]  

提示:

m == mat.length
n == mat[i].length
1 <= n, m <= 50
1 <= matrix[i][j] <= 10^5
矩阵中的所有元素都是不同的

分析

根据题意我们了解幸运数需要满足俩个条件这个数必须是在同一行的所有元素中是最小的并且在在同一列的所有元素中最大。

当我们看到此处就已经想到解法,我们只需要将遍历当前矩阵数组,先找到每一行中最小的,在看看此数是不是当前列中的最大的。如果是则就是一个幸运数,如果不则不是幸运数。

但是我们这样的实现方法时间复杂度会非常的高,在提示中的1 <= n, m <= 50,我们可以卡出矩阵数组的行数最长也就是50,我们的实现的方法应该不会超时,唯一的风险就是在列数没有最大值。

逐步实现

首先定义列数为常量colLen,值为数组长度 matrix[0].length,行数为rowLen,值为matrix[0].length,res为我需要的幸运数的集合

const colLen = matrix[0].length
const rowLen = matrix.length
const res = [];

通过俩层遍历找到每一行的最小值

for (let x = 0; x < rowLen; x++) {
        let minColIndex = 0
        for(let y = 1; y < colLen; y++){
            if(matrix[x][y] < matrix[x][minColIndex]){
                minColIndex = y
            }
        }
}

在通过遍历列数,看看当行中的最小值是否是列中的最大值,如果是则是幸运数push到数组res,如果不是则跳出本次循环。

for (let x = 0; x < rowLen; x++) {
    let minColIndex = 0
    for(let y = 1; y < colLen; y++){
        if(matrix[x][y] < matrix[x][minColIndex]){
            minColIndex = y
        }
    }
    for(let z = 0; z < rowLen; z++){
        if (matrix[z][minColIndex] > matrix[x][minColIndex]){
            break
        }
        if (z === matrix.length - 1){
                res.push(matrix[x][minColIndex])
        };
    }
}

代码实现

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var luckyNumbers = function (matrix) {
    const colLen = matrix[0].length
    const rowLen = matrix.length
    const res = [];
    
    for (let x = 0; x < rowLen; x++) {
        let minColIndex = 0
        for(let y = 1; y < colLen; y++){
            if(matrix[x][y] < matrix[x][minColIndex]){
                minColIndex = y
            }
        }
        for(let z = 0; z < rowLen; z++){
            if (matrix[z][minColIndex] > matrix[x][minColIndex]){
                break
            }
            if (z === matrix.length - 1){
                res.push(matrix[x][minColIndex])
            };
        }
    }
    return res;
};