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

[LeetCode]Longest Consecutive Sequence

时间:2015-04-18 10:09:13      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:leetcode

题意:在一堆无序元素中找到最长的连续串的长度,要求时间复杂度O(N)

思路:首先将元素放到set集合中,然后再判断,每次判断是否包含某元素的复杂度为O(1)
代码:

    public int longestConsecutive(int[] num) {
        int currLen = 0, longestLen = Integer.MIN_VALUE;
        Set<Integer> set = new HashSet<Integer>();
        for(int i : num){
            set.add(i);
        }
        int left,right,i;

        Iterator<Integer> it = set.iterator();
        while (it.hasNext()){
            i = it.next();
            currLen = 1;//当前长度
            left = i - 1;
            right = i + 1;
            while (set.contains(left)){//向下查找
                currLen ++;
                set.remove(left);
                left --;
            }
            while (set.contains(right)){//向上查找
                currLen ++;
                set.remove(right);
                right ++;
            }
            longestLen = Math.max(longestLen,currLen);
            set.remove(i);
            it = set.iterator();//需要重新赋值
        }

        return longestLen;
    }


[LeetCode]Longest Consecutive Sequence

标签:leetcode

原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/45110401

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