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
19
class Solution {
 public:
  vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
    vector<int> ans;
    vector<vector<int>> rowSum;

    for (int i = 0; i < mat.size(); ++i)
      rowSum.push_back({accumulate(mat[i].begin(), mat[i].end(), 0), i});

    ranges::sort(rowSum, [](const vector<int>& a, const vector<int>& b) {
      return a[0] == b[0] ? a[1] < b[1] : a[0] < b[0];
    });

    for (int i = 0; i < k; ++i)
      ans.push_back(rowSum[i][1]);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int[] kWeakestRows(int[][] mat, int k) {
    int[] ans = new int[k];
    int[][] candidates = new int[mat.length][2];

    for (int i = 0; i < mat.length; ++i) {
      candidates[i][0] = IntStream.of(mat[i]).sum();
      candidates[i][1] = i;
    }

    Arrays.sort(candidates, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);

    for (int i = 0; i < k; ++i)
      ans[i] = candidates[i][1];

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
    candidates = []

    for i, row in enumerate(mat):
      candidates.append([sum(row), i])

    candidates.sort(key=lambda c: (c[0], c[1]))

    return [i for _, i in candidates[:k]]