当前位置: 首页 > news >正文

从零开始的LeetCode刷题日记:128. 最长连续序列

一.相关链接

题目链接:128. 最长连续序列

二.心得体会

       这道题要求时间复杂度是O(n),这就告诉我们不能用排序的方法来做。

       如果这道题用排序的方法,那么就比较简单,只需要在排序之后便利整个数组,当找到有比当前索引元素值小1的数则插入<nums[i], iter->second + 1>。否则插入<nums[i], 1>。

       不使用排序的方法需要先对vector进行去重,然后选择性地对数组中元素进行遍历统计:只有当没有前置元素的时候,才进行向后遍历,统计连续序列长度。

三.代码

1)使用排序的代码:

class Solution {
public:int longestConsecutive(vector<int>& nums) {sort(nums.begin(), nums.end());unordered_map<int,int> m;for(int i : nums) {auto iter = m.find(i - 1);if(iter!=m.end()) {m.insert(pair<int,int>(i, iter->second + 1));}else m.insert(pair<int,int>(i, 1));}int ans = 0;for(int i : nums) {if(m[i] > ans) ans = m[i];}return ans;}
};

2)不使用排序:

class Solution {
public:int longestConsecutive(vector<int>& nums) {unordered_set<int> num_set;//去重for(const int& num : nums) {num_set.insert(num);}int ans = 0;for(const int& num : num_set) {if(!num_set.count(num - 1)) {int tem_ans = 1;int tem_num = num + 1;while(num_set.count(tem_num)) {tem_ans++;tem_num++;}if(tem_ans > ans) ans = tem_ans;}}return ans;}
};


http://www.mrgr.cn/news/95775.html

相关文章:

  • Spring Boot 整合 Nacos 注册中心终极指南
  • CentOS 7 更换 yum 源(阿里云)+ 扩展 epel 源
  • Jackson实现JSON数据的合并
  • vivo 湖仓架构的性能提升之旅
  • AI本地部署之dify
  • Redis 服务搭建
  • DeepSeek面试——模型架构和主要创新点
  • 《TCP/IP网络编程》学习笔记 | Chapter 21:异步通知 I/O 模型
  • springboot使用netty做TCP客户端
  • python面试高频考点(深度学习大模型方向)
  • 鸿蒙进行视频上传,使用 request.uploadFile方法
  • 大模型应用(Java)2025/3/24
  • LeetCode热题100JS(69/100)第十三天|34|33|153|4|20
  • 2025-3-24 leetcode刷题情况(动态规划——01背包)
  • 【HTML5游戏开发教程】零基础入门合成大西瓜游戏实战 | JS物理引擎+Canvas动画+完整源码详解
  • stm32-IIC
  • 运动仿真——phased.Platform
  • 手动创建Electron+React项目框架(建议直接看最后)
  • 项目日记 -云备份 -服务端配置信息模块
  • Spatial Multiplexing Power Save