Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions top-k-frequent-elements/DaleSeo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use std::collections::HashMap;

// TC: O(n)
// SC: O(n)
impl Solution {
pub fn top_k_frequent(nums: Vec<i32>, k: i32) -> Vec<i32> {
let mut freqs = HashMap::new();
for &num in &nums {
*freqs.entry(num).or_insert(0) += 1;
}

let mut buckets = vec![Vec::new(); nums.len() + 1];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

로직은 버킷소트로 선형시간 만족하게 잘 작성해주신 것 같아요 :)

러스트는 제가 처음 접해봐서 코드를 분석해보다가, 문득 궁금한게 생겨서 질문드려봅니다.
C++에서는 동적배열인 vector를 힙에 할당하는데, 러스트는 Vec::new()를 하게되면 마찬가지로 힙에 할당하게 될지, 메모리 해제는 어떤식으로 관리될지 궁금합니다.

추가로 동적배열의 시간/공간 복잡도는 아마 구현체 방식이 언어마다 비슷하리라 생각되어서 동일하다고 생각되는데 러스트도 마찬가지이겠죠?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dolphinflow86 님, 좋은 질문 감사합니다.

Rust의 Vec<T>도 C++의 vector처럼 동적 배열이고, 원소를 저장하는 버퍼는 힙에 할당됩니다. 다만 Vec::new() 자체는 보통 아직 버퍼를 할당하지 않고, 길이/용량이 0인 Vec 값을 만드는 것으로 이해하시면 됩니다. 실제 힙 할당은 push 등으로 원소가 들어가면서 용량이 필요해질 때 발생합니다.

메모리 해제는 Rust의 ownership/RAII 방식으로 관리됩니다. bucketsfreqs가 스코프를 벗어나면 Drop이 자동으로 호출되고, 내부 원소들을 정리한 뒤 힙 메모리도 해제됩니다.

시간/공간 복잡도도 일반적인 동적 배열과 거의 동일하게 봐도 될 것 같습니다.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@DaleSeo 자세한 답변 감사합니다 👍

for (num, freq) in freqs {
buckets[freq].push(num);
}

let mut top_nums = Vec::new();
for bucket in buckets.into_iter().rev() {
for num in bucket {
top_nums.push(num);
if top_nums.len() == k as usize {
return top_nums;
}
}
}

top_nums
}
}
Loading