1337.矩阵中攻击力最弱的K行(javascript)1337.TheKWeakestRowsinaMatrix
原创给你一个尺码 m * n 的矩阵 mat,矩阵由许多军事和民用组成,使用 1 和 0 表示。
请返回矩阵中最弱的战斗力。 k 行索引,从最弱到最强排序。
如果第 i 排队的士兵人数比第一个少。 j 排成一列,或两列士兵人数相同 i 小于 j,然后我们认为是第一个。 i 该线的战斗力高于第一线。 j 行弱。
军人 总是 在该行的顶部,即 1 始终出现在 0 之前。
You are given an m x n binary matrix mat of 1’s (representing soldiers) and 0’s (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1’s will appear to the left of all the 0’s in each row.
A row i is weaker than a row j if one of the following is true:
The number of soldiers in row i is less than the number of soldiers in row j.
Both rows have the same number of soldiers and i < j.
Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.
示例 1:
输入:mat =
[[1,1,0,0,0],
[1,1,1,1,0],
[1,0,0,0,0],
[1,1,0,0,0],
[1,1,1,1,1]],
k = 3
输出:[2,0,3]
解释:
每排士兵人数:
行 0 -> 2
行 1 -> 4
行 2 -> 1
行 3 -> 2
行 4 -> 5
将这些行从最弱到最强排序。 [2,0,3,1,4]
示例 2:
输入:mat =
[[1,0,0,0],
[1,1,1,1],
[1,0,0,0],
[1,0,0,0]],
k = 2
输出:[0,2]
解释:
每排士兵人数:
行 0 -> 1
行 1 -> 4
行 2 -> 1
行 3 -> 1
将这些行从最弱到最强排序。 [0,2,3,1]
提示:
- m == mat.length
- n == mat[i].length
- 2 <= n, m <= 100
- 1 <= k <= m
- matrix[i][j] 不是 0 就是 1
根据问题的含义,计算每排士兵的人数,
- 关键是行,值是存放的士兵人数。map中;
- 将map按士兵人数排序
map将伪数组map转换为新数组
数组由每个项进行子标记。1数字 - 获取二维数组中的每个下标0数字
-
返回k上一个数组
var sum1 = function (list) { return list.reduce((acr, cur) => { return acr + cur }) } var kWeakestRows = function (mat, k) { const map = new Map(); let ans = [] mat.forEach((item, index) => map.set(index, sum1(item))); var arrayObj = Array.from(map); arrayObj.sort(function (a, b) { return a[1] - b[1] }) arrayObj.forEach(function (value, key) { if (key < k) { ans.push(value[0]) } }) return ans };
用实施例1进行测试
//返回数组的和
var sum1 = function (list) {
return list.reduce((acr, cur) => {
return acr + cur
})
}
var kWeakestRows = function (mat, k) {
const map = new Map();
let ans = []
//存储列表的索引值(键),数组(值)的总和。map中
mat.forEach((item, index) => map.set(index, sum1(item)));
//console.log(map);
// [{0 => 2},
// {1 => 4},
// {2 => 1},
// {3 => 2},
// {4 => 5},]
var arrayObj = Array.from(map);
//console.log(arrayObj);
// 0: (2) [0, 2]
// 1: (2) [1, 4]
// 2: (2) [2, 1]
// 3: (2) [3, 2]
// 4: (2) [4, 5]
// length: 5
arrayObj.sort(function (a, b) {
return a[1] - b[1]
})
//console.log(arrayObj);
// 0: (2) [2, 1]
// 1: (2) [0, 2]
// 2: (2) [3, 2]
// 3: (2) [1, 4]
// 4: (2) [4, 5]
// length: 5
arrayObj.forEach(function (value, key) {
if (key < k) {
ans.push(value[0])
}
})
//console.log(ans);
//[2, 0, 3]
return ans
};
参考: 三、ES6合集之Map和Set
leetcode: https://leetcode-cn.com/problems/the-k-weakest-rows-in-a-matrix/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123


