Longest Consecutive Sequence 解答

Question

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.

Solution

一开始尝试用segment tree, heap等,发现时间复杂度不能达到线性。

后来参考别人答案,发现用HashSet计数的方法。

程序比较简单。

1. 遍历一遍数组,将所有元素存入set

2. 遍历数组。对于当前元素x,看x+1和x-1是否在set中。如果在,则remove,并且一直找到这个区间的边界。

 1 public class Solution {
 2     public int longestConsecutive(int[] nums) {
 3         Set<Integer> set = new HashSet<Integer>();
 4         for (int i : nums) {
 5             set.add(i);
 6         }
 7         int max = 0;
 8         int count;
 9         for (int i : nums) {
10             if (set.isEmpty()) {
11                 break;
12             }
13             count = 1;
14             int right = i + 1;
15             int left = i - 1;
16             set.remove(i);
17             // find right
18             while (set.contains(right)) {
19                 set.remove(right);
20                 count++;
21                 right++;
22             }
23             // find left
24             while (set.contains(left)) {
25                 set.remove(left);
26                 count++;
27                 left--;
28             }
29             max = Math.max(max, count);
30         }
31         return max;
32     }
33 }
原文地址:https://www.cnblogs.com/ireneyanglan/p/4944713.html