Skip to content

Commit b0fb81e

Browse files
committed
add 128
1 parent e9e0e7e commit b0fb81e

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[package]
2+
name = "S0128-longest-consecutive-sequence"
3+
version = "0.1.0"
4+
authors = ["Xargin <cao1988228@163.com>"]
5+
edition = "2018"
6+
7+
[dependencies]
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
struct Solution;
2+
3+
use std::collections::HashMap;
4+
use std::collections::HashSet;
5+
6+
#[derive(Clone, Debug)]
7+
struct Bounds {
8+
pub lower_bound: i32,
9+
pub upper_bound: i32,
10+
}
11+
12+
impl Solution {
13+
pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
14+
// 记录每个元素对应的上界、下界
15+
// 如果两个元素相连的话,那么这两个元素对应的上下界一定能连起来
16+
let mut bounds_m: HashMap<i32, Bounds> = HashMap::new();
17+
18+
// 记录出现过的元素,如果元素之前出现过,没必要再处理了
19+
let mut record_m: HashSet<i32> = HashSet::new();
20+
let mut max_len = 0;
21+
for num in nums {
22+
if record_m.contains(&num) {
23+
continue;
24+
}
25+
26+
let left = num - 1;
27+
let right = num + 1;
28+
let mut new_bounds = Bounds {
29+
upper_bound: num,
30+
lower_bound: num,
31+
};
32+
33+
if bounds_m.contains_key(&left) {
34+
let left_bounds = bounds_m.get(&left).unwrap();
35+
if left_bounds.upper_bound >= num {
36+
continue;
37+
}
38+
39+
if left_bounds.upper_bound == left {
40+
// 可以合并
41+
new_bounds.lower_bound = left_bounds.lower_bound;
42+
bounds_m.remove(&left);
43+
}
44+
}
45+
46+
if bounds_m.contains_key(&right) {
47+
let right_bounds = bounds_m.get(&right).unwrap();
48+
if right_bounds.lower_bound <= num {
49+
continue;
50+
}
51+
52+
if right_bounds.lower_bound == right {
53+
new_bounds.upper_bound = right_bounds.upper_bound;
54+
bounds_m.remove(&right);
55+
}
56+
}
57+
58+
bounds_m.insert(new_bounds.lower_bound, new_bounds.clone());
59+
bounds_m.insert(new_bounds.upper_bound, new_bounds.clone());
60+
max_len = max_len.max(new_bounds.upper_bound - new_bounds.lower_bound + 1);
61+
record_m.insert(num);
62+
}
63+
64+
max_len
65+
}
66+
}
67+
68+
fn main() {
69+
dbg!(Solution::longest_consecutive(vec![100, 4, 200, 1, 3, 2]));
70+
}

0 commit comments

Comments
 (0)