Row K is the least powerful row in the matrix

Title Description

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.

 

Example 1:

,1,0,0,0 Input: mat = [[1], [1,1,1,1,0],,0,0,0,0 [1],,1,0,0,0 [1], [1,1,1,1,1]], k = 3 Output:,0,3 [2] Explanation: The number of soldiers in each row is: - Row 0: 2 - Row 1: 4 - Row 2: 1 - Row 3: 2 - Row 4: 6 The rows ordered by The federal federal corporation to insistence that The costs be drastically reduced [2,0,3,1,4].Copy the code

Example 2:

,0,0,0 Input: mat = [[1], [1,1,1,1],,0,0,0 [1], [1,0,0,0]], k = 2 Output: [0, 2] Explanation: The number of soldiers in each row is: - Row 0: 1 - Row 1: 4 - Row 2: 1 - Row 3: 1 The rows ordered from The beginning to be ontarioed [0,2,3,1]Copy the code

 

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 2 <= n, m <= 100
  • 1 <= k <= m
  • matrix[i][j] is either 0 or 1.

Topic describes

You are given a matrix MAT of size m by n, consisting of a number of soldiers and civilians, represented by 1 and 0 respectively.

Return the index of the weakest k rows in the matrix, sorted from weakest to strongest.

If the ith row has fewer soldiers than the j row, or if the two rows have the same number of soldiers but I is less than j, then we consider the ith row less effective than the j row.

Soldiers are always at the top of the line, which means that the one always comes before the zero.

 

Example 1:

Input: mat = [,1,0,0,0 [1], [1,1,1,1,0],,0,0,0,0 [1],,1,0,0,0 [1], [1,1,1,1,1]], k = 3 output:,0,3 [2] : soldiers number in each row: Row 0 -> 2 row 1 -> 4 Row 2 -> 1 row 3 -> 2 Row 4 -> 5 Sort these rows from weakest to strongest to get [2,0,3,1,4]Copy the code

Example 2:

Input: mat = [,0,0,0 [1], [1,1,1,1],,0,0,0 [1], [1,0,0,0]], k = 2 output: [0, 2] explanation: the number of soldiers in the line: Row 0 -> 1 Row 1 -> 4 Row 2 -> 1 Row 3 -> 1 Sort these rows from weakest to strongest and you get [0,2,3,1]Copy the code

 

Tip:

  • m == mat.length
  • n == mat[i].length
  • 2 <= n, m <= 100
  • 1 <= k <= m
  • Matrix [I][J] is either 0 or 1

Their thinking

  1. Maps are used to store array references and subscripts
  2. The sorting
  3. Get the first k subscripts from the map

code

/**
 * @param {number[][]} mat
 * @param {number} k
 * @return {number[]}
 */
var kWeakestRows = function (mat, k) {
    const map = new Map();
    mat.forEach((a, i) => map.set(a, i));
    mat.sort();

    return Array.from({ length: k }, (_, i) => map.get(mat[i]));
};
Copy the code