博客
关于我
最长的连续元素序列长度(哈希表)
阅读量:368 次
发布时间:2019-03-04

本文共 1036 字,大约阅读时间需要 3 分钟。

题目描述

给定一个无序的整数类型数组,求最长的连续元素序列的长度。 例如: 给出的数组为[1000, 4, 2000, 1, 3, 2],

最长的连续元素序列为[1, 2, 3, 4]. 返回这个序列的长度:4 你需要给出时间复杂度在O(n)之内的算法

思路

  • 第一反应使用哈希表,然后是想到map,但题目要求时间复杂度O(n),map是有序的所以要用无序的,又输入是vector,所以使用同样是基于hash表的unorder_set
  • 接着只要遍历查找每个数的+1,-1的值是否存在,记录序列长度
  • 每次将序列长度更新为最长的
  • 哈希函数的使用方法
class Solution {   public:    /**     *      * @param num int整型vector      * @return int整型     */    int longestConsecutive(vector
& num) { // write code here // 使用哈希表 unordered_set
uset(num.begin(), num.end()); int res = 0; for(auto item:num){ int left = item - 1; int right = item + 1; int cnt = 1; // 遍历找left,left每次减一 while(uset.count(left) != 0){ uset.erase(left--); cnt++; } while(uset.count(right) != 0){ uset.erase(right++); cnt++; } // 每次更新最长的序列 res = max(res, cnt); } return res; }};

在这里插入图片描述

转载地址:http://yfdg.baihongyu.com/

你可能感兴趣的文章
Net与Flex入门
查看>>
Net任意String格式转换为DateTime类型
查看>>
net包之IPConn
查看>>
net发布的dll方法和类显示注释信息(字段说明信息)[图解]
查看>>
Net和T-sql中的日期函数操作
查看>>
Net处理html页面元素工具类(HtmlAgilityPack.dll)的使用
查看>>
Net操作Excel(终极方法NPOI)
查看>>
Net操作配置文件(Web.config|App.config)通用类
查看>>
net网络查看其参数state_dict,data,named_parameters
查看>>
Net连接mysql的公共Helper类MySqlHelper.cs带MySql.Data.dll下载
查看>>
NeurIPS(神经信息处理系统大会)-ChatGPT4o作答
查看>>
neuroph轻量级神经网络框架
查看>>
Neutron系列 : Neutron OVS OpenFlow 流表 和 L2 Population(7)
查看>>
new Blob()实现不同类型的文件下载功能
查看>>
New Concept English three (35)
查看>>
NEW DATE()之参数传递
查看>>
New Journey--工作五年所思所感小记
查看>>
new Queue(REGISTER_DELAY_QUEUE, true, false, false, params)
查看>>
New Relic——手机应用app开发达人的福利立即就到啦!
查看>>
new work
查看>>