-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlongest-harmonious-subsequence.rs
49 lines (38 loc) · 1.25 KB
/
longest-harmonious-subsequence.rs
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
40
41
42
43
44
45
46
47
48
49
#![allow(dead_code, unused, unused_variables)]
fn main() {}
struct Solution;
impl Solution {
pub fn find_lhs(nums: Vec<i32>) -> i32 {
let mut hash = std::collections::HashMap::<i32, i32>::new();
for &i in nums.iter() {
hash.entry(i).and_modify(|x| *x += 1).or_insert(1);
}
let mut res = 0;
for &i in nums.iter() {
let s = hash.get(&(i - 1));
let s1 = hash.get(&i).unwrap();
if s.is_some() {
if s1 + *s.unwrap() > res {
res = s1 - *s.unwrap();
}
}
}
res
}
pub fn find_lhs1(nums: Vec<i32>) -> i32 {
let mut hash = std::collections::HashMap::<i32, i32>::new();
let mut res = 0;
for &i in nums.iter() {
hash.entry(i).and_modify(|x| *x += 1).or_insert(1);
let s = hash.get(&(i - 1));
if s.is_some() && res < hash.get(&i).unwrap() + s.unwrap() {
res = hash.get(&i).unwrap() + s.unwrap()
}
let s = hash.get(&(i + 1));
if s.is_some() && res < hash.get(&i).unwrap() + s.unwrap() {
res = hash.get(&i).unwrap() + s.unwrap()
}
}
res
}
}