# Array - 128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

java：

```class Solution {

// online
public int longestConsecutive(int[] nums) {
if( nums == null ||nums.length == 0) return 0;

int res = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int n : nums) {
if(!map.containsKey(n)) {
int left = map.containsKey(n-1) ? map.get(n-1) : 0;
int right = map.containsKey(n+1) ? map.get(n+1) : 0;

int sum = left + right + 1;

res = Math.max(res, sum);
map.put(n, sum);

map.put(n - left, sum);
map.put(n + right, sum);
}
}

return res;
}

// offline
/* public int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0) return 0;

Set set = new HashSet();
for (int num : nums) set.add(num);

int ans =0;
for (int n : nums){
if (!set.contains(n-1)) {
int len = 0;
while (set.contains(n++)) ++len;
ans = Math.max(ans, len);
}
}

return ans;
}*/
}```

0 条评论

• ### Array - 219. Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two dist...

• ### Array - 283. Move Zeroes

Given an array nums, write a function to move all 0's to the end of it while mai...

• ### Dynamic Programming - 213. House Robber II

213. House Robber II You are a professional robber planning to rob houses along...

• ### LeetCode | 1.两数之和

上面的题就是 两数之和 题目的截图，同时 LeetCode 会根据选择的语言给出了一个类的定义或者函数的定义，然后在其中实现 两数之和 的解题过...

• ### Leetcode: Single Number III

Given an array of numbers nums, in which exactly two elements appear only once...

• ### leetcode之错误的集合

这里遍历一次数组，求出总和，并计算每个元素的count，同时找出重复的元素，之后根据自然数求和公式与现有总和的差值及重复的元素计算得出缺失的元素。

• ### leetcode之错误的集合

这里遍历一次数组，求出总和，并计算每个元素的count，同时找出重复的元素，之后根据自然数求和公式与现有总和的差值及重复的元素计算得出缺失的元素。

• ### Two Sum

Given an array of integers, return indices of the two numbers such that they add...

• ### 两数之和（TwoSum）

我工作2年已经感觉到危机感，正准备同时这面临着两个问题了，不如蹭现在还有来得及一起去把算法练起来吧，光看可不行得练。尽可能的把 https://leetcode...