-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
practice leetcode - longest consecutive sequence
- Loading branch information
Showing
3 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
7 changes: 7 additions & 0 deletions
7
src/practice/leetcode/longest_consecutive_sequence/Cargo.lock
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
6 changes: 6 additions & 0 deletions
6
src/practice/leetcode/longest_consecutive_sequence/Cargo.toml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
[package] | ||
name = "longest_consecutive_sequence" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
[dependencies] |
40 changes: 40 additions & 0 deletions
40
src/practice/leetcode/longest_consecutive_sequence/src/main.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
// https://leetcode.com/problems/longest-consecutive-sequence/ | ||
|
||
struct Solution; | ||
|
||
impl Solution { | ||
pub fn longest_consecutive(nums: Vec<i32>) -> i32 { | ||
use std::collections::HashMap; | ||
let mut cnt: HashMap<i32, i32> = HashMap::new(); | ||
let mut visited: HashMap<i32, bool> = HashMap::new(); | ||
let mut mark: HashMap<i32, bool> = HashMap::new(); | ||
for &n in &nums { | ||
mark.insert(n, true); | ||
} | ||
let mut ans = 0; | ||
for &n in &nums { | ||
if *visited.get(&n).unwrap_or(&false) { | ||
continue; | ||
} | ||
let mut itr = n; | ||
let mut nbr = 0; | ||
while !visited.get(&itr).unwrap_or(&false) && *mark.get(&itr).unwrap_or(&false) { | ||
nbr += 1; | ||
visited.insert(itr, true); | ||
itr += 1; | ||
} | ||
cnt.insert(n, nbr); | ||
if let Some(&next_cnt) = cnt.get(&itr) { | ||
*cnt.get_mut(&n).unwrap() += next_cnt; | ||
} | ||
ans = ans.max(*cnt.get(&n).unwrap()); | ||
} | ||
ans | ||
} | ||
} | ||
|
||
fn main() { | ||
let nums = vec![100, 4, 200, 1, 3, 2]; | ||
let result = Solution::longest_consecutive(nums); | ||
println!("{result}") | ||
} |