Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1873 from AkifhanIlgaz/0169
Browse files Browse the repository at this point in the history
Create: 0169-majority-element.rs
  • Loading branch information
tahsintunan authored Jan 5, 2023
2 parents 641452a + b3b22c8 commit a3d27f5
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions rust/0169-majority-element.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use std::collections::HashMap;

impl Solution {
// Time Complexity: O(n)
// Space Complexity: O(1)
// Boyer - Moore Algorithm
pub fn majority_element(nums: Vec<i32>) -> i32 {
let (mut res, mut count) = (0, 0);

for n in nums {
if count == 0 {
res = n;
}
count += if n == res { 1 } else { -1 };
}
res
}

// Time Complexity: O(n)
// Space Complexity: O(n)
// Hashmap
pub fn majority_element_2(nums: Vec<i32>) -> i32 {
let mut count = HashMap::new();

let (mut res, mut max_count) = (0, 0);

for num in nums {
*count.entry(num).or_insert(0) += 1;
res = if *count.get(&num).unwrap() > max_count {
num
} else {
res
};
max_count = i32::max(*count.get(&num).unwrap(), max_count);
}
res
}

// Time Complexity: O(nlogn)
// Space Complexity: O(1)
// Sorting
pub fn majority_element_3(nums: Vec<i32>) -> i32 {
// Since we are assured that there will be a majority element which occurs more than nums.len() / 2 times, majority element will be at nums.len() / 2 index
let mut nums = nums;
nums.sort();
nums[nums.len() / 2]
}
}

0 comments on commit a3d27f5

Please sign in to comment.