Skip to content

Update 0347-top-k-frequent-elements.rs #3056

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 13, 2023
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
16 changes: 7 additions & 9 deletions rust/0347-top-k-frequent-elements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,18 @@ impl Solution {
let mut map: HashMap<i32, i32> = HashMap::new();

for n in nums{
*map.entry(n).or_default() +=1;
*map.entry(n).and_modify(|val| *val+=1).or_default();
}

let mut freq: Vec<(i32, i32)> = map.into_iter().collect();

let res = if k == freq.len() as i32{
&freq
}else{
quick_select(&mut freq, k)
let res = match (k as usize).cmp(&freq.len()){
Ordering::Equal => &freq,
_ => quick_select(&mut freq, k),
};

res.into_iter()
.map(|&(n, _)| n)
.map(|&n| n.0)
.collect()
}
}
Expand All @@ -29,12 +28,11 @@ pub fn quick_select(slice: &mut [(i32, i32)], k: i32) -> &[(i32, i32)]{
for index in 1..slice.len(){
if slice[index].1 >= slice[pivot].1{
slice.swap(index, j);
j+=1;
}else{
slice.swap(index, i);
i+=1;
j+=1;
}
j+=1;
}

slice.swap(pivot, i - 1);
Expand All @@ -47,4 +45,4 @@ pub fn quick_select(slice: &mut [(i32, i32)], k: i32) -> &[(i32, i32)]{
Ordering::Greater => quick_select(&mut slice[pivot + 1..j], k),
Ordering::Equal => &slice[pivot..j],
}
}
}