↓快轉到主要內容
  1. LeetCode/

LeetCode 1337: The K Weakest Rows in a Matrix

·1 分鐘· ·
LeetCode Easy Array Binary-Search Sorting Heap-Priority-Queue
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-11-21

  • 提交紀錄:Accepted(一次通過)

解題思路
#

每一列的 1 都排在 0 前面,所以士兵數就是「第一個 0 的位置」,可以二分(Binary Search 模板一)。之後照 (士兵數, 列號) 排序,取前 k 個列號。

我的解法
#

class Solution:
    def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
        def soldiers(row):
            l, r = 0, len(row)
            while l < r:
                mid = (l + r) // 2
                if row[mid] == 1:
                    l = mid + 1
                else:
                    r = mid
            return l
        return sorted(range(len(mat)), key=lambda i: (soldiers(mat[i]), i))[:k]

我當時是直接 sum(row) 再丟進 heap,一樣會過;這裡用二分利用「1 都在前面」的性質。

複雜度
#

時間 O(m log n + m log m),空間 O(m)。

要特別避免的錯誤
#

  • 士兵數一樣時,列號小的比較弱。

面試口說整理
#

每列的士兵都在前面,所以我二分找第一個 0 得到士兵數,再用(士兵數, 列號)排序取前 k 個。時間 O(m log n + m log m)。

相關文章

LeetCode 506: Relative Ranks
·1 分鐘
LeetCode Easy Array Sorting Heap-Priority-Queue
LeetCode 506 解題筆記:把 index 按分數由高到低排序,前三名給獎牌,其他給名次的字串,放回原本的位置
LeetCode 1464: Maximum Product of Two Elements in an Array
·1 分鐘
LeetCode Easy Array Sorting Heap-Priority-Queue
LeetCode 1464 解題筆記:值都是正數,取最大的兩個數 a、b,答案是 (a - 1)(b - 1)
LeetCode 888: Fair Candy Swap
·1 分鐘
LeetCode Easy Array Hash-Table Binary-Search Sorting
LeetCode 888 解題筆記:交換 x 和 y 後總和相等,代表 y = x + (sumB - sumA) / 2;把 B 放進集合,逐一檢查 A 的 x
LeetCode 1051: Height Checker
·1 分鐘
LeetCode Easy Array Sorting Counting-Sort Bubble-Sort
LeetCode 1051 解題筆記:排序後跟原本的陣列逐一比較,數有幾個位置不同
LeetCode 594: Longest Harmonious Subsequence
·1 分鐘
LeetCode Easy Array Hash-Table Sliding-Window Sorting
LeetCode 594 解題筆記:子序列不用連續,所以只要計數,每個 x 看 x 和 x + 1 的次數加起來
LeetCode 349: Intersection of Two Arrays
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 解題筆記:兩個陣列各轉成集合取交集