「每日LeetCode」2022年2月15日

本文最后更新于:2023年3月19日 晚上

1380.矩阵中的幸运数

1380.矩阵中的幸运数

Category Difficulty Likes Dislikes
algorithms Easy (72.74%) 71 -

Tags
Companies
给你一个 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
* @lc app=leetcode.cn id=1380 lang=javascript
*
* [1380] 矩阵中的幸运数
*/

// @lc code=start
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var luckyNumbers = function (matrix) {
const res = [];
for (let i = 0; i < matrix.length; i++) {
const min = Math.min(...matrix[i]);
let j;
for (j = 0; j < matrix[i].length; j++) {
const element = matrix[i][j];
if (element === min) break;
}
let max = -Infinity;
for (let k = 0; k < matrix.length; k++) {
const num = matrix[k][j];
max = Math.max(num, max);
}
if (min === max) res.push(min);
}

return res;
};
// @lc code=end