128. Longest Consecutive Sequence

来源:互联网 发布:玄机科技工资 知乎 编辑:程序博客网 时间:2024/06/07 13:41

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;    }}


原创粉丝点击