标签: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