当前位置:网站首页>最长连续序列
最长连续序列
2022-06-28 14:51:00 【华为云】
title: 最长连续序列
date: 2022-04-22 11:33:47
tags: 每天进步一点点系列
题目
题目:最长连续序列
难度:中等
给定一个未排序的整数数组 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
题解:先排下序,用个一维dp数组,dp[n]记录长度,最后求出最大的dp值就行了,数组长度为0的先处理下就行了,注意点就是返回值默认值为1,先给dp数组都初始化为1,因为最小的连续长度肯定是包含自身也就是1
代码:
class Solution { public int longestConsecutive(int[] nums) { if(nums.length==0){ return 0; } //排序下 Arrays.sort(nums); //max初始化为1,因为最小的连续序列长度为1,避免数组中只有一个元素的情况,也可以在上面写if提前过滤 int max = 1; int[] dp = new int[nums.length]; //先填充个初始长度,包括本身,也就是1 Arrays.fill(dp,1); for(int i=1;i<nums.length;i++){ //比前一个大,那么就是连续的 if(nums[i]==nums[i-1]+1){ dp[i] = dp[i-1] + 1; } //和前一个相等,连续长度保持就行 if(nums[i]==nums[i-1]){ dp[i] = dp[i-1]; } max = Math.max(max,dp[i]); } return max; }}每日单词

以上就是最长连续序列(dp)全部内容
版权声明:
原创博主:牛哄哄的柯南
个人博客链接:https://www.keafmd.top/
看完如果对你有帮助,感谢点击下面的==一键三连==支持!
[哈哈][抱拳]

加油!
共同努力!
Keafmd
都看到这里了,下面的内容你懂得,让我们共同进步!
边栏推荐
- 名创优品通过上市聆讯:寻求双重主要上市 年营收91亿
- [C language] how to generate normal or Gaussian random numbers
- Vscode writes markdown file and generates pdf
- Leetcode (88) -- merge two ordered arrays
- openGauss内核:SQL解析过程分析
- Leetcode (167) -- sum of two numbers II - input ordered array
- functools:对callable对象的高位函数和操作(持续更新ing...)
- Ionq and Ge research confirmed that quantum computing has great potential in risk aggregation
- Softing epgate Pb series Gateway - integrates the Profibus bus into the ethernet/ip network
- 不要使用短路逻辑编写 stl sorter 多条件比较
猜你喜欢
随机推荐
324. 摆动排序 II : 不简单的构造题
sent2vec教程
[JS] Fibonacci sequence implementation (recursion and loop)
Do not use short circuit logic to write STL sorter multi condition comparison
单一职责原则
请问一下,是不是insert all这种oracle的批量新增没拦截?
动力电池,是这样被“瓜分”的
Introduction to common components of IOT low code platform
[MySQL learning notes 24] index design principles
js 判断字符串为空或者不为空
What are the benefits of this PMP certificate?
[MySQL learning notes 23] index optimization
叮!Techo Day 腾讯技术开放日如约而至!
What is the renewal fee for PMP certificate?
3. caller service call - dapr
币圈大地震:去年赚100万,今年亏500万
Talking from the little nematode -- tracing the evolution of nervous system and starting life simulation
Leetcode (167) -- sum of two numbers II - input ordered array
2022 operation of simulation test platform for 100 simulated questions of main principals of metal and nonmetal mines (underground mines)
The latest pycharm activation cracking code in 2022 is permanent_ Detailed installation tutorial (applicable to multiple versions)









