• 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
                
  • 相关阅读:
    react-redux
    Vue中常用的UI框架
    vue中router与route的区别
    H5新增input属性
    H5新增的input类型
    菜鸡对作用域链的理解
    自己对路由的一些理解
    浏览器缓存
    黄瓜的不定期更新面试题
    ajax封装
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13208003.html
Copyright © 2020-2023  润新知