Skip to content

Commit 82ea40b

Browse files
solves k weakest rows in a matrix
1 parent f0473ad commit 82ea40b

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@
342342
| 1323 | [Maximum 69 Number](https://leetcode.com/problems/maximum-69-number) | [![Java](assets/java.png)](src/Maximum69Number.java) | |
343343
| 1331 | [Rank Transform of An Array](https://leetcode.com/problems/rank-transform-of-an-array) | [![Java](assets/java.png)](src/RankTransformOfArray.java) | |
344344
| 1332 | [Remove Palindromic Subsequences](https://leetcode.com/problems/remove-palindromic-subsequences) | [![Java](assets/java.png)](src/RemovePalindromicSubSequences.java) | |
345-
| 1337 | [The K Weakest Rows In A Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix) | | |
345+
| 1337 | [The K Weakest Rows In A Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix) | [![Java](assets/java.png)](src/TheKWeakestRowsInAMatrix.java) | |
346346
| 1342 | [Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero) | | |
347347
| 1346 | [Check if N and It's Double Exist](https://leetcode.com/problems/check-if-n-and-its-double-exist) | | |
348348
| 1351 | [Count Negative Numbers In A Sorted Matrix](https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix) | | |

src/TheKWeakestRowsInAMatrix.java

+21-5
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,25 @@
33

44
public class TheKWeakestRowsInAMatrix {
55
public int[] kWeakestRows(int[][] mat, int k) {
6-
Queue<Row> minHeap = new PriorityQueue<>();
7-
for (int[] row: mat) {
8-
minHeap.add()
6+
final Queue<Row> minHeap = new PriorityQueue<>();
7+
for (int index = 0 ; index < mat.length ; index++) {
8+
minHeap.add(Row.from(mat[index], index));
99
}
10+
final int[] result = new int[k];
11+
for (int i = 0 ; i < result.length ; i++) {
12+
result[i] = minHeap.poll().index;
13+
}
14+
return result;
1015
}
1116

12-
private record Row(int index, int soldiers) implements Comparable<Row> {
17+
private static final class Row implements Comparable<Row> {
18+
private final int index;
19+
private final int soldiers;
20+
21+
private Row(int index, int soldiers) {
22+
this.index = index;
23+
this.soldiers = soldiers;
24+
}
1325

1426
@Override
1527
public int compareTo(Row other) {
@@ -20,7 +32,11 @@ public int compareTo(Row other) {
2032
}
2133

2234
private static Row from(int[] row, int index) {
23-
for (int)
35+
int soldiers = 0;
36+
for (int i = 0; i < row.length && row[i] == 1; i++) {
37+
soldiers++;
38+
}
39+
return new Row(index, soldiers);
2440
}
2541
}
2642
}

0 commit comments

Comments
 (0)