Longest Consecutive Sequence

来源:互联网 发布:联发科x10优化 编辑:程序博客网 时间:2024/06/07 21:08

题目:

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.

分析:

用一个set存储集合中的所有元素,

然后遍历数组的时候,查找set中是否有当前元素+1,-1之后的元素,同时删除掉;

因为连续的元素会在一次当中删除掉,进而得到这个连续段的最大长度,或者说这个连续段不论从哪个元素开始,得到的最大长度都是一样的,所以查找一次就够了!!

反之,其他连续段中的元素,这次查找过程是查不到的,也是删不掉的!

参考代码如下:

http://www.programcreek.com/2013/01/leetcode-longest-consecutive-sequence-java/

public class Solution {    public static int longestConsecutive(int[] num) {    // if array is empty, return 0    if (num.length == 0) {    return 0;    }         Set<Integer> set = new HashSet<Integer>();    int max = 1;         for (int e : num)    set.add(e);         for (int e : num) {    int left = e - 1;    int right = e + 1;    int count = 1;         while (set.contains(left)) {    count++;    set.remove(left);    left--;    }         while (set.contains(right)) {    count++;    set.remove(right);    right++;    }         max = Math.max(count, max);    }         return max;    }}


0 0
原创粉丝点击