|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +/** |
| 8 | + * 1341. The K Weakest Rows in a Matrix |
| 9 | + * |
| 10 | + * Given a m * n matrix mat of ones (representing soldiers) and zeros (representing civilians), |
| 11 | + * return the indexes of the k weakest rows in the matrix ordered from the weakest to the strongest. |
| 12 | + * A row i is weaker than row j, if the number of soldiers in row i is less than the number of soldiers in row j, |
| 13 | + * or they have the same number of soldiers but i is less than j. Soldiers are always stand in the frontier of a row, |
| 14 | + * that is, always ones may appear first and then zeros. |
| 15 | + * |
| 16 | + * Example 1: |
| 17 | + * Input: mat = |
| 18 | + * [[1,1,0,0,0], |
| 19 | + * [1,1,1,1,0], |
| 20 | + * [1,0,0,0,0], |
| 21 | + * [1,1,0,0,0], |
| 22 | + * [1,1,1,1,1]], |
| 23 | + * k = 3 |
| 24 | + * Output: [2,0,3] |
| 25 | + * Explanation: |
| 26 | + * The number of soldiers for each row is: |
| 27 | + * row 0 -> 2 |
| 28 | + * row 1 -> 4 |
| 29 | + * row 2 -> 1 |
| 30 | + * row 3 -> 2 |
| 31 | + * row 4 -> 5 |
| 32 | + * Rows ordered from the weakest to the strongest are [2,0,3,1,4] |
| 33 | + * |
| 34 | + * Example 2: |
| 35 | + * Input: mat = |
| 36 | + * [[1,0,0,0], |
| 37 | + * [1,1,1,1], |
| 38 | + * [1,0,0,0], |
| 39 | + * [1,0,0,0]], |
| 40 | + * k = 2 |
| 41 | + * Output: [0,2] |
| 42 | + * Explanation: |
| 43 | + * The number of soldiers for each row is: |
| 44 | + * row 0 -> 1 |
| 45 | + * row 1 -> 4 |
| 46 | + * row 2 -> 1 |
| 47 | + * row 3 -> 1 |
| 48 | + * Rows ordered from the weakest to the strongest are [0,2,3,1] |
| 49 | + * |
| 50 | + * Constraints: |
| 51 | + * m == mat.length |
| 52 | + * n == mat[i].length |
| 53 | + * 2 <= n, m <= 100 |
| 54 | + * 1 <= k <= m |
| 55 | + * matrix[i][j] is either 0 or 1. |
| 56 | + * */ |
| 57 | +public class _1341 { |
| 58 | + public static class Solution1 { |
| 59 | + public int[] kWeakestRows(int[][] mat, int k) { |
| 60 | + List<int[]> list = new ArrayList<>(); |
| 61 | + for (int i = 0; i < mat.length; i++) { |
| 62 | + int soldiers = 0; |
| 63 | + for (int j = 0; j < mat[0].length; j++) { |
| 64 | + if (mat[i][j] == 1) { |
| 65 | + soldiers++; |
| 66 | + } else { |
| 67 | + break; |
| 68 | + } |
| 69 | + } |
| 70 | + list.add(new int[]{i, soldiers}); |
| 71 | + } |
| 72 | + Collections.sort(list, (a, b) -> a[1] == b[1] ? a[0] - b[0] : a[1] - b[1]); |
| 73 | + int[] result = new int[k]; |
| 74 | + int i = 0; |
| 75 | + while (i < k) { |
| 76 | + result[i] = list.get(i++)[0]; |
| 77 | + } |
| 78 | + return result; |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments