Longest Consecutive Sequence

来源:互联网 发布:软件测试怎么学 编辑:程序博客网 时间:2024/06/06 10:50

Q:

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:

public class Solution {    public int longestConsecutive(int[] num) {        if (num.length == 0)            return 0;        HashSet<Integer> set = new HashSet<Integer>();        for (int i = 0; i < num.length; i++)            set.add(num[i]);        int count = 1;        int max = count;        for (int i = 0; i < num.length; i++) {            if (set.contains(num[i])) {                int next = num[i] + 1;                set.remove(num[i]);                while (set.contains(next)) {                    count++;                    set.remove(next);                    next++;                }                int prev = num[i] - 1;                while (set.contains(prev)) {                    count++;                    set.remove(prev);                    prev--;                }                max = Math.max(max, count);            }            count = 1;        }        return max;    }}


0 0