Skip to content

Commit

Permalink
practice leetcode - longest consecutive sequence
Browse files Browse the repository at this point in the history
  • Loading branch information
vuquang23 committed Jan 15, 2025
1 parent f06a791 commit 43c2cd2
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
7 changes: 7 additions & 0 deletions 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.

6 changes: 6 additions & 0 deletions src/practice/leetcode/longest_consecutive_sequence/Cargo.toml
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 src/practice/leetcode/longest_consecutive_sequence/src/main.rs
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}")
}

0 comments on commit 43c2cd2

Please sign in to comment.