Leetcode-The-K-Weakest-Rows-in-a-Matrix
Leetcode 1337. The K Weakest Rows in a Matrix 解題心得
題目描述
在這道題目中,我們被給予一個 m * n
的二維矩陣 mat
,其中 mat[i][j]
代表第 i 行士兵在第 j 列的狀態(1 為存在,0 為不存在),且每行的士兵狀態是非遞增的。我們需要找出矩陣中前 k 個最弱的行(即士兵數量最少的行),並回傳他們的索引值。若有多行士兵數量相同,則選擇索引較小的行。
大概像這樣:
1 |
|
解題思路
這題的解法很直覺,就是先計算每一排的人數,然後再排序,最後回傳前 k
個排的索引值。
Code
一行解法:
1 |
|
這裡使用了蠻多的 lambda
,與 map
,以及生成式。
簡單解釋一下:
list(map(sum,mat))
會將mat
中的每一排加總,並回傳一個list
。enumerate
會回傳一個tuple
,第一個元素是索引值,第二個元素是list(map(sum,mat))
中的元素。sorted
會將enumerate
的結果依照第二個元素排序,並回傳一個list(tuple)
。[:k]
會回傳排序後的前k
個元素。
大致上是這些,然後生成式跟map使用得當,可以讓程式碼更簡潔。
Runtime 100 ms Beats 86.17%
Memory 16.6 MB Beats 94.18%
Leetcode-The-K-Weakest-Rows-in-a-Matrix
https://hibana2077.github.io/post/Leetcode-The-K-Weakest-Rows-in-a-Matrix.html