当前位置:网站首页>算法---矩阵中战斗力最弱的 K 行(Kotlin)
算法---矩阵中战斗力最弱的 K 行(Kotlin)
2022-06-24 08:21:00 【小米科技Android 研发曹新雨】
题目
给你一个大小为 m * n 的矩阵 mat,矩阵由若干军人和平民组成,分别用 1 和 0 表示。
请你返回矩阵中战斗力最弱的 k 行的索引,按从最弱到最强排序。
如果第 i 行的军人数量少于第 j 行,或者两行军人数量相同但 i 小于 j,那么我们认为第 i 行的战斗力比第 j 行弱。
军人 总是 排在一行中的靠前位置,也就是说 1 总是出现在 0 之前。
示例 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
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/the-k-weakest-rows-in-a-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解决方法
fun kWeakestRows(mat: Array<IntArray>, k: Int): IntArray {
var pair = Array(mat.size) {
Array(2) {
0 } }
mat.forEachIndexed {
index, ints ->
run {
pair[index][0] = index
mat[index].forEach {
pair[index][1] += it
}
}
}
Arrays.sort(pair,0,pair.size) {
o1, o2 -> if (o1[1] > o2[1]) 1 else if (o1[1] == o2[1]) 0 else -1 }
val result = IntArray(k) {
0 }
for (i in 0 until k){
result[i] = pair[i][0]
}
return result
}
总结
1.因为军人始终在前面,所以还可以根据index 判断当前行的战斗力,二分法更快的找到最大的战斗力,而不是全部都遍历
边栏推荐
猜你喜欢

In depth analysis of Apache bookkeeper series: Part 3 - reading principle
![[redis implements seckill business ①] seckill process overview | basic business implementation](/img/a3/9a50e83ece43904a3a622dcdb05b3c.png)
[redis implements seckill business ①] seckill process overview | basic business implementation
![[GDB debugging tool] | how to debug under multithreading, multiprocessing and running programs](/img/b5/38a53c88240c4308452d0208173461.png)
[GDB debugging tool] | how to debug under multithreading, multiprocessing and running programs

关于thinkphp5 使用模型save()更新数据提示 method not exist:think\db\Query-&gt; 报错解决方案

Easyexcel single sheet and multi sheet writing

PRCT-1400 : 未能执行 getcrshome解决方法
Depens:*** but it is not going to be installed

【Redis實現秒殺業務①】秒殺流程概述|基本業務實現

Zero foundation self-study SQL course | having clause

L01_ How is an SQL query executed?
随机推荐
Solution: the word of jmeter5.5 on the win11 lower interface is very small
Talking about the knowledge of digital transformation
Tools
e的lnx为什么等于x
Chapter 7 operation bit and bit string (III)
The border problem after the focus of input
PHP使用递归和非递归方式实现创建多级文件夹
When programmers are asked if they can repair computers... | daily anecdotes
Learning Tai Chi Maker - esp8226 (XIII) OTA
【Eureka注册中心】
php文件锁
什么情况下应该使用GridFS?
学习太极创客 — ESP8226 (十三)OTA
latex公式及表格识别
Target of cmake command_ compile_ options
Microblog writing - flow chart - sequence chart - Gantt chart - Mermaid flow chart - good results
关于thinkphp5 使用模型save()更新数据提示 method not exist:think\db\Query-&gt; 报错解决方案
浮点数表示法(总结自CS61C和CMU CSAPP)
转:三星电子CEO:一切决策都要从认清自己开始
Jincang KFS replicator installation (oracle-kes)