JavaScript 矩阵中的幸运数字
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/12 0:12:17
给定一个 m * n 的不同数字矩阵,我们必须以任意顺序返回二维数组(矩阵)中的所有幸运数字。
幸运数字是矩阵的一个元素,它是行中最小的元素,也是列中最大的元素。
例如 − 如果输入数组是 −
const arr = [ [3,7,8], [9,11,13], [15,16,17] ];
那么输出应该是 −
const output = [15];
因为 15 是唯一的幸运数字,因为它是同一行中的最小值,也是同一列中的最大值。
示例
其代码为 −
const arr = [
[3,7,8],
[9,11,13],
[15,16,17]
];
const luckyNumbers = (arr, res = []) => {
let M = arr.length, N = arr[0].length;
let min = Array(M).fill( Infinity);
let max = Array(N).fill(-Infinity);
for (let i = 0; i < M; ++i)
for (let j = 0; j < N; ++j)
min[i] = Math.min(min[i], arr[i][j]),
max[j] = Math.max(max[j], arr[i][j]);
for (let i = 0; i < M; ++i)
for (let j = 0; j < N; ++j)
if (min[i] == max[j])
res.push(arr[i][j]);
return res;
};
console.log(luckyNumbers(arr));
输出
控制台中的输出将是 −
[15]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

