-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmajority_element.rs
More file actions
39 lines (38 loc) · 938 Bytes
/
majority_element.rs
File metadata and controls
39 lines (38 loc) · 938 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/// https://leetcode.com/problems/majority-element/
/// 寻找数组中出现次数大于len/2次的元素
fn majority_element(nums: Vec<i32>) -> i32 {
let n = nums.len();
if n == 1 {
return nums[0];
}
let half = (n / 2) as u16;
let mut cnt = std::collections::HashMap::with_capacity(n);
for num in nums {
if let Some(count) = cnt.get_mut(&num) {
if half.eq(count) {
return num;
}
*count += 1;
} else {
cnt.insert(num, 1_u16);
}
}
unsafe {
std::hint::unreachable_unchecked();
}
}
fn majority_element_best(nums: Vec<i32>) -> i32 {
let mut count: u16 = 0;
let mut candidate = 0;
for num in nums {
if count == 0 {
candidate = num;
}
if num == candidate {
count += 1;
} else {
count -= 1;
}
}
candidate
}