Longest Consecutive Sequence

Longest Consecutive Sequence

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

Example

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

Clarification

Your algorithm should run in O(n) complexity.

Solution: 建一个hash表 对每一个num[i]上下浮动寻找num[i]+1, num[i]+2, …, 和num[i]-1, num[i]-2, …是不是在表里 如果找到的话就把该数从hash表里删除避免重复查找,所以建表时间是O(n) 每个数只会被访问一次,所以时间复杂度是O(n).

public int longestConsecutive(int[] num) {
    Set<Integer> numSet = new HashSet<>();
    for (int i = 0; i < num.length; i++) {
        numSet.add(num[i]);
    }
    int maxLength = 0;
    for (int i = 0; i < num.length; i++) {
        if (numSet.contains(num[i])) {
            int length = 1;
            int curr = num[i] - 1 ;
            while (numSet.contains(curr)) {
                numSet.remove(curr);
                length++;
                curr--;
            }
            curr = num[i] + 1;
            while (numSet.contains(curr)) {
                numSet.remove(curr);
                length++;
                curr++;
            }
            if (length > maxLength) {
                maxLength = length;
            }
        }
    }
    return maxLength;
}
FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *