
✨ 문제
The K Weakes Rows in a Matrix
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.
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/description/
✨ 최종코드
class Solution {
public int[] kWeakestRows(int[][] mat, int k) {
// Step 1: 각 행의 병사 수 세기
int[][] counts = new int[mat.length][2];
for (int i = 0; i < mat.length; i++) {
int count = 0;
for (int j = 0; j < mat[i].length; j++) {
if (mat[i][j] == 1) {
count++;
} else {
break; // 행은 정렬되어 있으므로 첫 0이 나타나면 끝입니다.
}
}
counts[i][0] = count;
counts[i][1] = i;
}
// Step 2: 병사 수에 따라 정렬, 병사 수가 같으면 행 인덱스로 정렬
Arrays.sort(counts, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
// Step 3: 가장 약한 k개의 행 인덱스 추출
int[] weakestRows = new int[k];
for (int i = 0; i < k; i++) {
weakestRows[i] = counts[i][1];
}
return weakestRows;
}
}
'알고리즘 > 99클럽' 카테고리의 다른 글

✨ 문제
The K Weakes Rows in a Matrix
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.
https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/description/
✨ 최종코드
class Solution { public int[] kWeakestRows(int[][] mat, int k) { // Step 1: 각 행의 병사 수 세기 int[][] counts = new int[mat.length][2]; for (int i = 0; i < mat.length; i++) { int count = 0; for (int j = 0; j < mat[i].length; j++) { if (mat[i][j] == 1) { count++; } else { break; // 행은 정렬되어 있으므로 첫 0이 나타나면 끝입니다. } } counts[i][0] = count; counts[i][1] = i; } // Step 2: 병사 수에 따라 정렬, 병사 수가 같으면 행 인덱스로 정렬 Arrays.sort(counts, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); // Step 3: 가장 약한 k개의 행 인덱스 추출 int[] weakestRows = new int[k]; for (int i = 0; i < k; i++) { weakestRows[i] = counts[i][1]; } return weakestRows; } }