반응형
https://leetcode.com/problems/fruits-into-baskets-ii/description
전수조사로 해결한 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
i번째 바구니를 사용했는지 여부를 확인하기 위해 vector checked 변수를 mut으로 선언해줍니다.
📔 풀이과정
📑 i번째 fruit를 담을 j번째 basket 크기를 비교
fruits에 대해 iter수행하며 for_each마다 basket에 enumerate 했을 때 j번째가 현재 fruit 이상이라면 담을 수 있으므로 j번째 checked 를 true로 바꿔줍니다.
📑 checked배열에서 false인 값을 변수 unplaced
📑 시간 복잡도
O(n^2)
📑 공간 복잡도
O(n)
📔 정답 출력 | 반환
unplaced를 반환합니다.
📕 Code
📔 Rust
impl Solution {
pub fn num_of_unplaced_fruits(fruits: Vec<i32>, baskets: Vec<i32>) -> i32 {
let mut checked = vec![false; baskets.len()];
fruits.iter().for_each(|fruit| {
if let Some((j, _)) = baskets
.iter()
.enumerate()
.find(|(j, basket)| fruit <= basket && !checked[*j])
{
checked[j] = true;
}
});
let unplaced = checked.iter().filter(|&&x| !x).count() as i32;
unplaced
}
}
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Brute Force' 카테고리의 다른 글
(Python3) - LeetCode (Medium) : 2429. Minimize XOR (0) | 2025.01.15 |
---|---|
(Python3) - LeetCode (Medium) : 2657. Find the Prefix Common Array of Two Arrays (0) | 2025.01.14 |
(Python3) - LeetCode (Medium) : 916. Word Subsets (0) | 2025.01.10 |
(Python3) - LeetCode (Easy) : 3042. Count Prefix and Suffix Pairs I (0) | 2025.01.08 |
(Python3) - LeetCode (Easy) : 1408. String Matching in an Array (0) | 2025.01.07 |