2022-03-23
use std::collections::HashMap;
impl Solution {
pub fn contains_duplicate(nums: Vec<i32>) -> bool {
let mut hmap = HashMap::new();
for num in nums {
match hmap.get(&num) {
Some(x) => {
return true;
},
None => {
hmap.insert(num,true);
},
}
}
return false;
}
}
2022-04-06
impl Solution {
pub fn max_sub_array(nums: Vec<i32>) -> i32 {
use std::cmp::max;
let mut ans = nums[0];
let mut sum = 0;
for x in nums {
sum = x + max(sum, 0);
ans = max(ans, sum);
}
return ans;
}
}
2022-04-11
impl Solution {
pub fn single_number(nums: Vec<i32>) -> i32 {
use std::collections::HashMap;
let mut haveNum = HashMap::new();
for num in &nums {
let count = haveNum.entry(num).or_insert(0);
*count += 1;
}
for num in &nums {
let count = haveNum.entry(num).or_insert(0);
if *count == 1 {
return *num;
}
}
return 0;
}
}
2022-04-12
(169. 多数元素)[https://leetcode-cn.com/problems/majority-element/]
impl Solution {
pub fn majority_element(nums: Vec<i32>) -> i32 {
use std::collections::HashMap;
let mut haveNum = HashMap::new();
for num in &nums {
let count = haveNum.entry(num).or_insert(0);
*count += 1;
}
for num in &nums {
let count = haveNum.entry(num).or_insert(0);
if *count > nums.len()/2 {
return *num;
}
}
return 0;
}
}