diff --git a/README.md b/README.md index ba0e9e2..d272eb6 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/codewars/majority_element.rs b/src/codewars/majority_element.rs new file mode 100644 index 0000000..fb1d5bb --- /dev/null +++ b/src/codewars/majority_element.rs @@ -0,0 +1,19 @@ +use std::collections::HashMap; + +pub fn majority_element(numbers: Vec) -> 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])) + } +} diff --git a/src/codewars/mod.rs b/src/codewars/mod.rs index c0ebbb1..71e7393 100644 --- a/src/codewars/mod.rs +++ b/src/codewars/mod.rs @@ -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; @@ -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; @@ -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;