leetcode地址:算法
https://leetcode.com/problems/longest-consecutive-sequence/description/數組
難度:hardapp
描述:spa
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.code
Your algorithm should run in O(n) complexity.排序
Example:ip
Input: [100, 4, 200, 1, 3, 2] Output: 4 Explanation: The longest consecutive elements sequence is . Therefore its length is 4.[1, 2, 3, 4]
解題思路:element
這題說難不難,說簡單也不簡單。簡單的地方在於它的解法一點也不復雜,很容易理解,難的地方在於若是以前沒有作過相似的題,可能一會兒不容易想到。leetcode
咱們能夠這麼看這個問題,這個數組中的全部的數確定是由一系列的連續值組成的。能夠想象將數組排序後,中間會有一些跳躍的點,從而將整個數組分隔成一個個短的連續值。咱們的目的就是要找出整個短的連續值中長度最長的那個。以一個連續值組內的任意一個數字爲切入點,咱們最終都應該能找到這個連續組,因此對於一個小的連續組,咱們只須要以其中的任意一個數字爲切入點,不須要重複地遍歷到每一個數字,那樣就會形成大量的重複計算。rem
咱們的算法具體步驟以下:
首先將數組的數字存入一個HashSet中;
而後遍歷數組,若是當前的數字在hashSet中不存在,說明它所在的連續組已經被處理過了,所以直接進入下一個循環。
若是當前數字存在,那麼咱們接下來以這個數組爲切入點,分別向前和向後連續查找,知道set中找不到連續值爲止,此時咱們就找到了當前數字所在的連續組,計算它的長度,與記錄的最大長度比較,若是當前的長度更長,就更新記錄的最大長度值。
完成遍歷就找到了最大長度。
代碼:
public int longestConsecutive(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
set.add(nums[i]);
}
int longest = 0;
for (int i = 0; i < nums.length; i++) {
if (!set.contains(nums[i])) {
continue;
}
int cur = nums[i];
int len = 1;
set.remove(cur);
int pre = cur - 1, next = cur + 1;
while (set.contains(pre)) {
set.remove(pre);
len++;
pre--;
}
while (set.contains(next)) {
set.remove(next);
len++;
next++;
}
if (len > longest) {
longest = len;
}
}
return longest;
}
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 . Therefore its length is 4.[1, 2, 3, 4]