无序整形数组,如何找到最长连续序列长度,时间复杂度O(n)
来源:互联网 发布:穿越时光的地铁知乎 编辑:程序博客网 时间:2024/06/01 09:56
import java.util.HashMap;
import java.util.Map;public class LongestConsecutive{ Map<Integer,Integer> map=new HashMap<>(); public int longestConsecutive(int[] r){ int res=0; for (int i : r) { int left=(map.containsKey(i-1))?map.get(i-1):0; int right=(map.containsKey(i+1))?map.get(i+1):0; int sum=left+right+1; map.put(i, sum); res=Math.max(res,sum); //{5=1, 6=3, 71=1, 7=1, 88=1, 90=1} not update neighbors, the count will be wrong when 8 is put. because sum for 7 is not right //extend to boundary of the sequence. pay attention. it is i-left and i+right. map.put(i-left, sum); map.put(i+right, sum); } return res; } public static void main(String[] args) { int[] r = { 71, 88, 90, 7, 5, 6, 63, 74, 89, 8 }; System.out.println(new LongestConsecutive().longestConsecutive(r)); }}Because it requires O(n) complexity, we can not solve the problem by sorting the array first. Sorting takes at least O(nlogn) time.
阅读全文
0 0
- 无序整形数组,如何找到最长连续序列长度,时间复杂度O(n)
- O(n)时间找出无序数组中最长的连续递增序列
- 算法-子数组连续序列最大和其时间复杂度如何从O(n^3)到O(n)
- 给定无序自然数数组,求最大连续自然数个数,时间复杂度为O(n)
- 给定无序自然数数组,求最大连续自然数个数,时间复杂度为O(n)
- 无序数组中找到最长连续子序列
- 1~n无序数组时间复杂度为O(n)排序
- 1~n无序数组时间复杂度为O(n)排序
- 首个正数,给定一个无序整形数组,找出第一个不在数组里的正整数。要求时间复杂度0(n),空间复杂度o(1)
- 两个无序数组分别叫A和B,长度分别是m和n,求中位数,要求时间复杂度O(m+n),空间复杂度O(1) 。
- 最长有序子序列 时间复杂度O(n^2)
- 无序数组中最长连续序列
- 无序数组中最长非降子序列长度
- 数组进行排序,时间复杂度O(N)&&求无序数组的中位数
- 无序序列中O(n)时间复杂度寻找最小(最大)的K个数
- 删除无序数组中跳跃重复值并排序(时间复杂度为O(n))
- 最长连续序列(O(n)算法)
- 最长连续序列(O(n),C++版)
- 求平均成绩
- bzoj 1036 树链剖分 解题报告
- java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
- 一个view如何同时响应onTouch和onClick事件
- 5-12 两个数的简单计算器 (10分)
- 无序整形数组,如何找到最长连续序列长度,时间复杂度O(n)
- Maven
- 设计模式-创建型软件设计模式(三)
- Stereo match 基本原理介绍
- KMP字符串匹配
- Python 将模块作为脚本来执行
- 记一次失败的oracle安装过程
- AsyncTash基础创建规则与例子
- gcc和g++的区别