Skip to content

Commit

Permalink
majority-element
Browse files Browse the repository at this point in the history
  • Loading branch information
nt-sivan committed May 17, 2024
1 parent 5881e33 commit 39de318
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 0 deletions.
7 changes: 7 additions & 0 deletions majority-element/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions majority-element/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = "majority-element"
version = "0.1.0"
edition = "2021"

[dependencies]
5 changes: 5 additions & 0 deletions majority-element/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
mod solution;
use crate::solution::Solution;
fn main() {
println!("Hello, world!{}", Solution::majority_element(vec![3, 3, 2]));
}
37 changes: 37 additions & 0 deletions majority-element/src/solution.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use std::collections::HashMap;

pub struct Solution;
impl Solution {
pub fn majority_element(nums: Vec<i32>) -> i32 {
let compare = (nums.len()+1) as i32 / 2;
let mut map = HashMap::new();

for num in nums {
let mut val = 1;
if map.contains_key(&num) {
val = *map.get(&num).unwrap() + val;
}
map.insert(num.clone(), val);
if val >= compare {
return num;
}
}

0

}
}

#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_three() {
assert_eq!(3,Solution::majority_element(vec![3, 2, 3]));
}

#[test]
fn test_two() {
assert_eq!(2,Solution::majority_element(vec![2, 2, 1, 1, 1, 2, 2]));
}
}
1 change: 1 addition & 0 deletions majority-element/title.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
2024-05-17 多数元素

0 comments on commit 39de318

Please sign in to comment.