【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
  在CODE上查看代码片 派生到我的代码片
  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. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值