128. Longest Consecutive Sequence

网友投稿 643 2022-11-11

128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

Intuition

It turns out that our initial brute force solution was on the right track, but missing a few optimizations necessary to reach \mathcal{O}(n)O(n) time complexity.

Algorithm

This optimized algorithm contains only two changes from the brute force approach: the numbers are stored in a HashSet (or Set, in Python) to allow \mathcal{O}(1)O(1) lookups, and we only attempt to build sequences from numbers that are not already part of a longer sequence. This is accomplished by first ensuring that the number that would immediately precede the current number in a sequence is not present, as that number would necessarily be part of a longer sequence.

class Solution { public int longestConsecutive(int[] nums) { Set num_set = new HashSet(); for (int num : nums) { num_set.add(num); } int longestStreak = 0; for (int num : num_set) { if (!num_set.contains(num-1)) { int currentNum = num; int currentStreak = 1; while (num_set.contains(currentNum+1)) { currentNum += 1; currentStreak += 1; } longestStreak = Math.max(longestStreak, currentStreak); } } return

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:107. Binary Tree Level Order Traversal II
下一篇:Maven仓库加载顺序的实例解析
相关文章

 发表评论

暂时没有评论,来抢沙发吧~