Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4ac0fd5

Browse files
committed
complete longest consecutive sequence using rustlang
1 parent 1058be3 commit 4ac0fd5

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

‎src/solution.rs‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,4 +101,53 @@ impl Solution {
101101
}
102102
return result;
103103
}
104+
105+
/// [128.Longest Consecutive Sequence](https://leetcode.cn/problems/longest-consecutive-sequence/description/)
106+
///
107+
/// Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
108+
///
109+
/// You must write an algorithm that runs in O(n) time.
110+
///
111+
/// Example 1:
112+
///
113+
/// Input: nums = [100,4,200,1,3,2]
114+
/// Output: 4
115+
/// Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
116+
///
117+
/// Example 2:
118+
///
119+
/// Input: nums = [0,3,7,2,5,8,4,6,0,1]
120+
/// Output: 9
121+
///
122+
/// Constraints:
123+
///
124+
/// 0 <= nums.length <= 10^5
125+
/// -10^9 <= nums[i] <= 10^9
126+
pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
127+
let mut exist: HashMap<i32, bool> = HashMap::new();
128+
for num in nums {
129+
exist.insert(num, true);
130+
}
131+
132+
let mut longest = 0;
133+
for (&num, _) in exist.iter() {
134+
if let Some(&ok) = exist.get(&(num - 1)) {
135+
if ok {
136+
continue;
137+
}
138+
}
139+
140+
let mut length = 1;
141+
let mut n = num;
142+
while let Some(&ok) = exist.get(&(n + 1)) {
143+
if !ok {
144+
break;
145+
}
146+
length += 1;
147+
n += 1;
148+
}
149+
longest = std::cmp::max(longest, length)
150+
}
151+
return longest;
152+
}
104153
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /