zoukankan      html  css  js  c++  java
  • 1337. The K Weakest Rows in a Matrix

    Given a m * n matrix mat of ones (representing soldiers) and zeros (representing civilians), return the indexes of the k weakest rows in the matrix ordered from the weakest to the strongest.

    A row i is weaker than row j, if the number of soldiers in row i is less than the number of soldiers in row j, or they have the same number of soldiers but i is less than j. Soldiers are always stand in the frontier of a row, that is, always ones may appear first and then zeros.

    对每行二分搜索统计1的个数,然后['index': index, 'count': count] 按照count排序,拿到前k个的index就是答案

    class Solution(object):
        def kWeakestRows(self, mat, k):
            """
            :type mat: List[List[int]]
            :type k: int
            :rtype: List[int]
            """
            count = []
            for row in mat:
                l = 0
                r = len(row) - 1
                while l <= r:
                    mid = (l + r) // 2
                    if row[mid] == 1:
                        l = mid + 1
                    else:
                        r = mid - 1
                count.append({"index": len(count), "count": l})
            count = sorted(count, key=lambda x: x["count"])
            ans = []
            for i in range(0, k, 1):
                ans.append(count[i]["index"])
            return ans
                
  • 相关阅读:
    UVA 12545 Bits Equalizer
    UVA 1610 Party Games
    UVA 1149 Bin Packing
    UVA 1607 Gates
    UVA 12627 Erratic Expansion
    UVA10562-Undraw the Trees(递归)
    UVA10129-Play on Words(欧拉路径)
    UVA816-Abbott's Revenge(搜索进阶)
    UVA1103-Ancient Messages(脑洞+dfs)
    UVA839-Not so Mobile
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13208003.html
Copyright © 2011-2022 走看看