Skip to content

1337. The K Weakest Rows in a Matrix 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class 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
17
18
19
class 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,
                (a, b)
                    -> a.getKey().equals(b.getKey()) ? a.getValue().compareTo(b.getValue())
                                                     : a.getKey().compareTo(b.getKey()));

    for (int i = 0; i < k; ++i)
      ans[i] = rowSums[i].getValue();

    return ans;
  }
}
1
2
3
4
5
class Solution:
  def kWeakestRows(self, mat: list[list[int]], k: int) -> list[int]:
    rowSums = [(sum(row), i) for i, row in enumerate(mat)]
    rowSums.sort(key=lambda x: (x[0], x[1]))
    return [i for _, i in rowSums[:k]]