From 586803c39b195549396ff60bcb4f456d733c3158 Mon Sep 17 00:00:00 2001 From: marina <138340846+bt3gl-cryptographer@users.noreply.github.com> Date: Wed, 2 Aug 2023 14:17:23 -0700 Subject: [PATCH] Create largest_k_matrix.py --- heaps/largest_k_matrix.py | 57 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 heaps/largest_k_matrix.py diff --git a/heaps/largest_k_matrix.py b/heaps/largest_k_matrix.py new file mode 100644 index 0000000..ac038a6 --- /dev/null +++ b/heaps/largest_k_matrix.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# author: bt3gl + +''' +You are given an m x n binary matrix mat of 1's (representing soldiers) +and 0's (representing civilians). The soldiers are positioned in front +of the civilians. That is, all the 1's will appear to the left of +all the 0's in each row. + +A row i is weaker than a row j if one of the following is true: + +The number of soldiers in row i is less than the number of soldiers in row j. +Both rows have the same number of soldiers and i < j. +Return the indices of the k weakest rows in the matrix ordered +from weakest to strongest. +''' + + + def k_weakest_row(self, mat, k): + + m = len(mat) + n = len(mat[0]) + + def binary_search(row): + + low = 0 + high = n + + while low < high: + + mid = (low + high) // 2 + if row[mid] == 1: + low = mid + 1 + else: + high = mid + + return low + + + pq = [] + for i, row in enumerate(mat): + + strength = binary_search(row) + entry = (-strength, -i) + if len(pq) < k or entry > pq[0]: + heapq.heappush(pq, entry) + if len(pq) > k: + heapq.heappop(pq) + + indexes = [] + while pq: + strength, i = heapq.heappop(pq) + + indexes.append(-i) + + return indexes[::-1]