본문 바로가기
알고리즘/LeetCode

LeetCode: 1337. The K Weakest Rows in a Matrix

by 패쓰킴 2025. 8. 20.
728x90

https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/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:

Input: mat = 
[[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]], 
k = 3
Output: [2,0,3]
Explanation: 
The number of soldiers in each row is: 
- Row 0: 2 
- Row 1: 4 
- Row 2: 1 
- Row 3: 2 
- Row 4: 5 
The rows ordered from weakest to strongest are [2,0,3,1,4].
Example 2:

Input: mat = 
[[1,0,0,0],
 [1,1,1,1],
 [1,0,0,0],
 [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 weakest to strongest are [0,2,3,1].
 

Constraints:

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

 

풀이

sort 하지 않고 반환해야하는 배열을 만들 때 제자리에 들어가도록 코드를 작성했다.

class Solution {
    func kWeakestRows(_ mat: [[Int]], _ k: Int) -> [Int] {
        var soldiers = Array(repeating: 0, count: mat.count)
        var check = Array(repeating: false, count: mat.count)
        
        for i in 0 ..< mat.count {
            let row = mat[i]
            let value = (row.reduce(0,+)) - 1
            let element = check[value]
            
            if element == false {
                soldiers[value] = i
                check[value] = true
            } else {
                for j in value ..< check.count {
                    if check[j] == false {
                        soldiers[j] = i
                        check[j] = true
                    }
                }
            }
        }
        
        let soldierCount = soldiers.compactMap{ $0 }
        return Array(soldierCount.prefix(k))
    }
}

틀림!

m과 n의 개수는 동일하지 않다는 것을 간과했음

이 부분까지 코드를 넣으면 오히려 더 복잡해질 것 같아서 sort를 하는 걸로 결정했더니 바로 통과됐다.

class Solution {
    func kWeakestRows(_ mat: [[Int]], _ k: Int) -> [Int] {
        var tuple = [(Int,Int)]()
        
        for i in 0 ..< mat.count {
            let sum = mat[i].reduce(0,+)
            tuple.append((i,sum))
        }
        
        let sorted = tuple.sorted { l, r in
            if l.1 == r.1 {
                return l.1 > r.1
            }
            return l.1 < r.1
        }
        
        let result = sorted.map{ $0.0 }.prefix(k)
        
        return Array<Int>(result)
    }
}

struct Tests {
    private let solution = Solution()
    
    @Test func test1() async throws {
        #expect(solution.kWeakestRows([[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])
    }
    
    @Test func test2() async throws {
        #expect(solution.kWeakestRows([[1,0,0,0],
                                       [1,1,1,1],
                                       [1,0,0,0],
                                       [1,0,0,0]], 2) == [0,2])
    }
    
    @Test func test3() async throws {
        #expect(solution.kWeakestRows([[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])
    }
    
    @Test func test4() async throws {
        #expect(solution.kWeakestRows([[1,1,1,1,1,1],
                                       [1,1,1,1,1,1],
                                       [1,1,1,1,1,1]], 1) == [0])
    }
}
728x90

'알고리즘 > LeetCode' 카테고리의 다른 글

LeetCode: 104. Maximum Depth of Binary Tree  (1) 2025.08.27
LeetCode: 100. Same Tree  (0) 2025.08.22
LeetCode: 888. Fair Candy Swap  (0) 2025.08.19
LeetCode: 704. Binary Search  (0) 2025.08.17
LeetCode: 441. Arranging Coins  (0) 2025.08.14

댓글