Array Binary Search Heap (Priority Queue) Matrix Sorting 1337. The K Weakest Rows in a Matrix ¶ Time: Space: C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18class Solution { public: vector<int> kWeakestRows(vector<vector<int>>& mat, int k) { vector<int> ans; vector<pair<int, int>> rowSums; // (sum(mat[i]), i) for (int i = 0; i < mat.size(); ++i) rowSums.emplace_back(accumulate(mat[i].begin(), mat[i].end(), 0), i); ranges::sort(rowSums, ranges::less{}, [](const pair<int, int>& rowSum) { return rowSum; }); for (int i = 0; i < k; ++i) ans.push_back(rowSums[i].second); return ans; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17class Solution { public int[] kWeakestRows(int[][] mat, int k) { int[] ans = new int[k]; Pair<Integer, Integer>[] rowSums = new Pair[mat.length]; for (int i = 0; i < mat.length; ++i) rowSums[i] = new Pair<>(Arrays.stream(mat[i]).sum(), i); Arrays.sort(rowSums, Comparator.comparingInt(Pair<Integer, Integer>::getKey) .thenComparingInt(Pair<Integer, Integer>::getValue)); for (int i = 0; i < k; ++i) ans[i] = rowSums[i].getValue(); return ans; } } 1 2 3 4class Solution: def kWeakestRows(self, mat: list[list[int]], k: int) -> list[int]: rowSums = [(sum(row), i) for i, row in enumerate(mat)] return [i for _, i in sorted(rowSums)[:k]] Was this page helpful? Thanks for your feedback! Thanks for your feedback! Help us improve this page by using our feedback form.