leetCode 128.最长连续序列
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
示例 1:
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
示例 2:
输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9
class Solution {
public int longestConsecutive(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
if(nums.length == 1){
return 1;
}
Set<Integer> numset = new HashSet<>();
for(int num: nums){
numset.add(num);
}
int longestStreak = 0;
for(Integer num : numset) {
if(!numset.contains(num - 1)) {
int currentNum = num;
int currentStreak = 1;
while(numset.contains(currentNum + 1)){
currentNum++;
currentStreak++;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
}
结果
执行用时分布
27ms
击败56.66%使用 Java 的用户
消耗内存分布
65.27MB
击败10.55%使用 Java 的用户
2,先排序,这个比上一个好点
class Solution {
public int longestConsecutive(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
Arrays.sort(nums);
int pre = nums[0];
int max = Integer.MIN_VALUE;
int count = 1;
for(int i = 1; i < nums.length; i++) {
if(nums[i] == pre){
continue;
}
if((nums[i] - pre) == 1){
count++;
}else{
max = Math.max(max,count);
count = 1;
}
pre = nums[i];
}
return Math.max(max,count);
}
}
执行用时分布
11ms
击败99.95%使用 Java 的用户
消耗内存分布
55.47MB
击败69.73%使用 Java 的用户