【Leetcode】Longest Consecutive Sequence

题目链接:https://leetcode.com/problems/longest-consecutive-sequence/
题目:

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.

思路:

因为要不断地确认 一个数的+1、-1是否在数组中,如果遍历数组来查找显然时间复杂度要大于O(n),考虑用HashSet可以方便的知道一个元素是否在集合中,如果一个元素+1/-1都不在集合中,则删去该元素,并且每一个元素判断后都删除,则时间复杂度为O(n)。
算法:

[java]  view plain  copy
 
  1. public int longestConsecutive(int[] nums) {  
  2.     int max = 1;  
  3.     Set<Integer> set = new HashSet<Integer>();  
  4.     for (int i = 0; i < nums.length; i++) {  
  5.         set.add(nums[i]);  
  6.     }  
  7.     for (int i = 0; i < nums.length; i++) {  
  8.         int length = 1// 当前元素连续长度  
  9.         if (set.contains(nums[i] + 1) || set.contains(nums[i] - 1)) {  
  10.             int cur = nums[i];  
  11.             while (set.contains(cur + 1)) {  
  12.                 length++;  
  13.                 set.remove(cur + 1);  
  14.                 cur++;  
  15.             }  
  16.             cur = nums[i];  
  17.             while (set.contains(cur - 1)) {  
  18.                 length++;  
  19.                 set.remove(cur - 1);  
  20.                 cur--;  
  21.             }  
  22.         }  
  23.         set.remove(nums[i]);  
  24.         max = Math.max(length, max);  
  25.     }  
  26.     return max;  
  27. }  

你可能感兴趣的:(【Leetcode】Longest Consecutive Sequence)