Skip to content

Commit

Permalink
leetcode: Add longest-consecutive-sequence
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Dec 7, 2023
1 parent 183c4a3 commit fb10ac9
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
7 changes: 7 additions & 0 deletions leetcode/0128.longest-consecutive-sequence/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "lc-0128-longest-consecutive-sequence"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
29 changes: 29 additions & 0 deletions leetcode/0128.longest-consecutive-sequence/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright (c) 2023 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be
// found in the LICENSE file.

pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
let mut nums = nums;
nums.sort();

let mut ans = 0;
let mut seq_len = 1;
for i in 0..(nums.len() - 1) {
if nums[i] + 1 == nums[i + 1] {
seq_len += 1;
} else {
ans = ans.max(seq_len);
seq_len = 1;
}
}
ans = ans.max(seq_len);
ans
}

fn main() {
let nums = vec![100, 4, 200, 1, 3, 2];
assert_eq!(longest_consecutive(nums), 4);

let nums = vec![0, 3, 7, 2, 5, 8, 4, 6, 0, 1];
assert_eq!(longest_consecutive(nums), 9);
}

0 comments on commit fb10ac9

Please sign in to comment.