Longest Consecutive Sequence

来源:互联网 发布:dns劫持后的域名来路 编辑:程序博客网 时间:2021/10/19 07:16
Problem:

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.


用了HashMap。
Solution:
public class Solution {
    public int longestConsecutive(int[] num) {
        if(num==null||num.length==0)
             return 0;
        int maxLen = 1;
        HashMap<Integer, Integer> seqRec = new HashMap<>();
        
        int front,rear;
        for(int i=0;i<num.length;i++)
        {
             if(seqRec.containsKey(num[i]))
                 continue;
             front = 0;
             rear = 0; 
             if(seqRec.containsKey(num[i]+1))
             {
                 front = seqRec.get(num[i]+1);
              }
             if(seqRec.containsKey(num[i]-1))
             {
                 rear = seqRec.get(num[i]-1);
              }
        
             seqRec.put(num[i]+front,front+rear+1);
             seqRec.put(num[i]-rear,front+rear+1);
             seqRec.put(num[i],front+rear+1);

             if(front+rear+1>maxLen)
                 maxLen = front+rear+1;
        }
        return maxLen;
    }
}
0 0