码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Consecutive Sequence

时间:2015-03-11 21:23:53      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

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)快速的查找任何一个数值

Longest Consecutive Sequence

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4330763.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!