[LeetCode]Longest Consecutive Sequence

来源:互联网 发布:maya导入unity3d 编辑:程序博客网 时间:2024/05/16 11:31

题目描述

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.

Your algorithm should run in O(n) complexity.

给定以未排序数组,以O(n)的时间复杂度求出其中可以组成最长连续数列的长度。


解题思路

   
     如果允许 O(n log n) 的复杂度,那么可以先排序,然后扫描即可。
    可是本题要求 O(n)。由于序列里的元素是无序的,又要求 O(n),首先要想到用哈希表。具体步骤如下:
  1. 将数组中元素添加到HashSet中;
  2. 将当前元素向右扩张,直到不连续为止,同时删除包含在HashSet中的元素;
  3. 将当前元素向左扩张,直到不连续为止,同时删除包含在HashSet中的元素;
  4. 重复步骤2和3直到循环完;

代码


public static int longestConsecutive(int[] num) {if (num.length == 0)return 0;if (num.length == 1)return 1;HashSet<Integer> hashSet = new HashSet<Integer>();//添加元素到hashSetfor (int i = 0; i < num.length; i++) {hashSet.add(num[i]);}int maxLen = 0;for (int i = 0; i < num.length; i++) {int tempLen = 1, tempNum;//将当前元素向右扩张,直到不连续为止,同时删除包含在hasSet中的元素tempNum = num[i] + 1;while (hashSet.contains(tempNum)) {hashSet.remove(tempNum);tempLen++;tempNum++;}//将当前元素向左扩张,直到不连续为止,同时删除包含在hashSet中的元素;tempNum = num[i] - 1;while (hashSet.contains(tempNum)) {hashSet.remove(tempNum);tempLen++;tempNum--;}//比较获取最大长度if (tempLen > maxLen)maxLen = tempLen;if (maxLen >= num.length - i)break;}return maxLen;}


0 0