128. 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.


public class Solution {
    public int longestConsecutive(int[] nums) {
        HashSet hs = new HashSet();
        
        for(int i : nums) {
            hs.add(i);
        }
        
        int max = 0;
        for(int i : nums) {
            int cnt = 1;
            hs.remove(i);
            int tmp = i;
            while(hs.contains(tmp-1)) {
                hs.remove(tmp-1);
                tmp--;
                cnt++;
            }
            tmp = i;
            while(hs.contains(tmp+1)) {
                hs.remove(tmp+1);
                tmp++;
                cnt++;
            }
            max = Math.max(max, cnt);
        }
        return max;
    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章