一、原題
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.
一、中文
給出一個數組,求出裏面能夠組成的最長連續子數組的長度並返回
三、舉例
比如數組[100, 4, 200, 1, 3, 2]中的最長子數組的長度就是[1, 2, 3, 4]
四、思路
首先對數組進行排序,然後將排序後的數組進行查找,從最左邊開始,如果相鄰就加一,如果不相鄰就將其置零
五、程序
import java.util.*;
public class Solution {
//發現連續的子字符串
public int longestConsecutive(int[] num) {
//排序
Arrays.sort(num);
int max = 1;
int count = 1;
for(int i = 1; i < num.length; i++){
if((num[i] - num[i-1]) == 1){
count++;
if(count > max){
max = count;
}
}else if(num[i] - num[i-1] == 0){
continue;
}else{
count = 1;
}
}
return max;
}
}