Skip to content

Commit

Permalink
Added majority element solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Dec 17, 2024
1 parent 3c87d7a commit e3e2edd
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ programming challenges completed in other languages.
- [Final Value of Variable After Operations](https://leetcode.com/problems/final-value-of-variable-after-performing-operations/)
- [Substring With Distinct Characters](https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/)
- [Remove Element](https://leetcode.com/problems/remove-element)
- [Majority Element](https://leetcode.com/problems/majority-element)

#### Medium

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

pub fn majority_element(numbers: Vec<i32>) -> i32 {
let freq = numbers.into_iter().fold(HashMap::new(), |mut acc, curr| {
*acc.entry(curr).or_insert(0) += 1;
acc
});
freq.into_iter().max_by_key(|e| e.1).unwrap().0
}

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

#[test]
fn calculates_majority_element() {
assert_eq!(2, majority_element(vec![1, 2, 2, 1, 2]))
}
}
7 changes: 4 additions & 3 deletions src/codewars/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ mod first_non_consecutive;
mod frequency_sort;
mod gps;
mod josephus;
mod lazy_repeater;
mod majority_element;
mod max_profit;
mod multiplication;
mod multiplication_table;
Expand All @@ -29,6 +31,7 @@ mod nearest_prime;
mod not_secure;
mod nth_power;
mod order;
mod parse_number;
mod pascal_case;
mod people_on_the_bus;
mod perimeter;
Expand All @@ -43,10 +46,8 @@ mod sort_numbers;
mod spinning_words;
mod square;
mod stocks;
mod sum_digits_power;
mod summation;
mod sumpairs;
mod valid_parentheses;
mod valid_spacing;
mod lazy_repeater;
mod parse_number;
mod sum_digits_power;

0 comments on commit e3e2edd

Please sign in to comment.