[LeetCode]Longest Consecutive Sequence

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.


public class Solution {
    public int longestConsecutive(int[] num) {
    	PriorityQueue<Integer> pq = new PriorityQueue<>();
    	for(int i:num){
    		pq.add(i);
    	}
    	int res = 0;
    	int maxRes = 0;
    	while(pq.size()>0){
    		int i=pq.poll();
    		if(pq.size()>0&&i==pq.peek()-1){
    			res++;
    		}else if(pq.size()>0&&i==pq.peek()){
    			continue;
    		}else{
    			maxRes = Math.max(res, maxRes);
    			res = 0;
    		}
    	}
    	return maxRes+1;
    }
}


你可能感兴趣的:(java,LeetCode)