Skip to content

Commit a3d27f5

Browse files
authored
Merge pull request #1873 from AkifhanIlgaz/0169
Create: 0169-majority-element.rs
2 parents 641452a + b3b22c8 commit a3d27f5

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

rust/0169-majority-element.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
use std::collections::HashMap;
2+
3+
impl Solution {
4+
// Time Complexity: O(n)
5+
// Space Complexity: O(1)
6+
// Boyer - Moore Algorithm
7+
pub fn majority_element(nums: Vec<i32>) -> i32 {
8+
let (mut res, mut count) = (0, 0);
9+
10+
for n in nums {
11+
if count == 0 {
12+
res = n;
13+
}
14+
count += if n == res { 1 } else { -1 };
15+
}
16+
res
17+
}
18+
19+
// Time Complexity: O(n)
20+
// Space Complexity: O(n)
21+
// Hashmap
22+
pub fn majority_element_2(nums: Vec<i32>) -> i32 {
23+
let mut count = HashMap::new();
24+
25+
let (mut res, mut max_count) = (0, 0);
26+
27+
for num in nums {
28+
*count.entry(num).or_insert(0) += 1;
29+
res = if *count.get(&num).unwrap() > max_count {
30+
num
31+
} else {
32+
res
33+
};
34+
max_count = i32::max(*count.get(&num).unwrap(), max_count);
35+
}
36+
res
37+
}
38+
39+
// Time Complexity: O(nlogn)
40+
// Space Complexity: O(1)
41+
// Sorting
42+
pub fn majority_element_3(nums: Vec<i32>) -> i32 {
43+
// 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
44+
let mut nums = nums;
45+
nums.sort();
46+
nums[nums.len() / 2]
47+
}
48+
}

0 commit comments

Comments
 (0)