Skip to content

Commit

Permalink
Added sort by increasing frequency solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Jul 23, 2024
1 parent c7d1f61 commit db5edfa
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ other languages.
- Remove From Sorted Array (https://leetcode.com/problems/remove-duplicates-from-sorted-array/)
- Sort the People (https://leetcode.com/problems/sort-the-people)
- Max Repeating Substring (https://leetcode.com/problems/maximum-repeating-substring/)
- Sort by Increasing Frequency (https://leetcode.com/problems/sort-array-by-increasing-frequency)

#### Medium

Expand Down
23 changes: 23 additions & 0 deletions src/leetcode/freq_sort.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use std::collections::HashMap;

pub fn frequency_sort(mut numbers: Vec<i32>) -> Vec<i32> {
let mut counter: HashMap<i32, i32> = HashMap::new();
for x in numbers.iter() {
*counter.entry(*x).or_default() += 1;
}

numbers.sort_by_key(|n| (counter.get(n).unwrap(), -n));
numbers
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn items_sorted_by_frequency() {
let numbers = vec![2, 3, 1, 3, 2];
let actual = frequency_sort(numbers);
assert_eq!(vec![1, 3, 3, 2, 2], actual)
}
}
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,4 @@ mod x_kind;
mod remove_duplicates;
mod sort_people;
mod max_repeating_substr;
mod freq_sort;

0 comments on commit db5edfa

Please sign in to comment.