Longest Consecutive Sequence

Longest Consecutive Sequence

问题:

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

思路:

  HashSet进行存储

我的代码:

复制代码
public class Solution {
    public int longestConsecutive(int[] num) {
        if(num == null || num.length == 0)  return 0;
        Set<Integer> set = new HashSet<Integer>();
        for(int i = 0; i < num.length; i++)
        {
            set.add(num[i]);
        }
        int maxLen = 0;
        for(int i = 0; i < num.length; i++)
        {
            if(set.contains(num[i]))
            {
                int tmp = num[i] - 1;
                int len = 1;
                set.remove(num[i]);
                while(set.contains(tmp))
                {
                    set.remove(tmp);
                    len++;
                    tmp--;
                }
                tmp = num[i] + 1;
                while(set.contains(tmp))
                {
                    set.remove(tmp);
                    len++;
                    tmp++;
                }
                maxLen = Math.max(maxLen,len);
            }
        }
        return maxLen;
    }
}
View Code
复制代码

学习之处:

  数组映射成,用HashSet进行存储可以在O(1)快速的查找任何一个数值

posted on   zhouzhou0615  阅读(119)  评论(0编辑  收藏  举报

导航

< 2025年1月 >
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示