数组中最长的连续序列(longest consecutive sequence)

来源:互联网 发布:淘宝论坛 编辑:程序博客网 时间:2024/04/29 05:47

题目:

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.

思路:

对于数组中任意元素K,找比它的数K+1,K+2,…和比它小的数K-1,K-2,…。这种连续序列的最大长度。

java实现

public int longestConsecutive(int[] num) {        Set<Integer> set = new HashSet<Integer>();        for(int n : num){            set.add(n);        }        int max = 1;        for(int n : num){            if(set.remove(n)){                int sum = 1;                int small = n - 1;                int big = n + 1;                while(set.remove(small)){                    sum++;                    small--;                }                while(set.remove(big)){                    sum++;                    big++;                }                max = Math.max(sum, max);            }        }        return max;    }
阅读全文
0 0
原创粉丝点击