当前位置:网站首页>【力扣】128. 最长连续序列
【力扣】128. 最长连续序列
2022-08-09 14:58:00 【漆黑丶】
题目:
给定一个未排序的整数数组 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
提示:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
答案:
class Solution {
public int longestConsecutive(int[] nums) {
if(nums.length == 0) return 0;
Arrays.sort(nums);
int sum = 1, max = 0;
for(int i = 0; i < nums.length - 1; i++){
//System.out.println(nums[i] + 1 + " " + nums[i+1]);
if(nums[i] == nums[i + 1]) continue;
if((nums[i] + 1) == nums[i + 1]){
sum++;
}else{
max = Math.max(sum, max);
sum = 1;
}
}
return Math.max(sum, max);
}
}
边栏推荐
猜你喜欢
随机推荐
【深度学习】SVM解决线性不可分情况(八)
交叉编译 Crypto++
【学习笔记】win10报0xc0000221错误无法开机
【论文阅读】Deep Learning for Image Super-resolution: A Survey(DL超分辨率最新综述)
【工具使用】Modbus Slave软件使用详解
什么是跨境电商测评?
ResNet 残差网络 一些粗略的理解
22考研中国地质大学-总结
[Deep Learning] SVM solves the linear inseparable situation (8)
【知识分享】Modbus通信协议详解
解决pyqt5 DLL load failed: 找不到指定的程序的问题
【深度学习】目标检测之评价指标
XGB系列-XGB参数指南
【Postgraduate Work Weekly】(Week 7)
Faster R-CNN 论文总结
【研究生工作周报】(第十周)
hugging face tutorial - Chinese translation - model summary
【研究生工作周报】(第三周)
NoUniqueBeanDefinitionException和JSON乱码处理出现异常
Android面试题基础集锦《一》