728x90
오늘의 문제
LeetCode - The K Weakest 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.
제한사항
- m == mat.length
- n == mat[i].length
- 2 <= n, m <= 100
- 1 <= k <= m
- matrix[i][j] is either 0 or 1.
입출력 예
mat | k | return |
[[1,1,0,0,0], [1,1,1,1,0], [1,0,0,0,0], [1,1,0,0,0], [1,1,1,1,1]] |
3 | [2, 0, 3] |
[[1,0,0,0], [1,1,1,1], [1,0,0,0], [1,0,0,0]] |
2 | [0, 2] |
풀이
import java.util.*;
class Solution {
public int[] kWeakestRows(int[][] mat, int k) {
List<int[]> list = new ArrayList<>();
for(int[] m: mat) Arrays.sort(m);
// 각 행의 1의 개수 세기
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 = mat[i].length - j;
break;
}
}
list.add(new int[]{count, i});
}
// 1의 개수가 적은 순 정렬 (같으면 인덱스 기준으로 오름차순 정렬)
Collections.sort(list, (a, b) -> a[0] == b[0] ? Integer.compare(a[1], b[1]) : Integer.compare(a[0], b[0]));
int[] answer = new int[k];
for (int i=0; i<k; i++) {
answer[i] = list.get(i)[1];
}
return answer;
}
}
1이 적은 행을 k개 리턴하는 문제였다. 각 행을 정렬해주어 1이 나오면 break를 하고 count 변수에 1의 개수를 담아주었다. 이후 list를 통해 인덱스에 1이 몇 개 있는지 확인하고, 1개 개수가 적은 순서대로 정렬을 한다. list 값의 1번 인덱스가 행의 인덱스이기 때문에 이를 k개 만큼 뽑아 배열로 담아 return 한다.
출처: LeetCode, https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/
728x90
'코딩테스트 연습 > 99클럽' 카테고리의 다른 글
[99클럽] 99클럽 코테 스터디 40일차 TIL - 그리디 (Greedy) (0) | 2024.06.28 |
---|---|
[99클럽] 99클럽 코테 스터디 38일차 TIL - 힙 (Heap) (0) | 2024.06.26 |
[99클럽] 99클럽 코테 스터디 37일차 TIL - 스택 (Stack) (0) | 2024.06.25 |
[99클럽] 99클럽 코테 스터디 36일차 TIL - 스택 (Stack) (0) | 2024.06.24 |
[99클럽] 99클럽 코테 스터디 35일차 TIL - 큐 (Queue) (0) | 2024.06.23 |