LeetCode LCR 119.最长连续序列

LCR 119.最长连续序列

题面:

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

示例:

input nums = [100,4,200,1,3,2]

output 4

解析:
  • 这道题目简单的思路就是,对nums中的数字进行排序,设本次遍历到的数字为num,判断num + 1是否是下一个不等于num的数字。
  • 优化:
    • 针对于下一个出现的数字而言,num/num + 1/others,我们可以通过降重操作来保证下一个为num + 1/others,我们一般常用的实现就是set,而set的底层就是哈希表,相对于HashMap而言,HashSet仅对键进行操作。于是乎,我们可以通过哈希表查询来完成num + 1是否存在来推进最长连续序列,这样就省去了排序所带来的时间消耗。
    • 注意:若num - 1在当前set中,意味着最长连续序列,一定不是从num向后推进的。即若[num, y]满足连续序列的要求,[num - 1, y]一定也是满足要求的,故可以不判断。
  • n l o g ( n ) → n nlog(n)\rightarrow n nlog(n)→n
复杂度

时间复杂度
O ( n ) O(n) O(n)
空间复杂度
O ( n ) O(n) O(n)

Code
c++ 复制代码
// C++
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> s;
        for (auto num : nums)
        {
            s.insert(num);
        }
        int ans = 0;
        for (int x : s)
        {
            if (s.count(x - 1))
            {
                continue;
            }
            int y = x + 1;
            while (s.count(y)) 
            {
                y++;
            }
            ans = max(ans, y - x);
        }
        return ans;
    }
};
python 复制代码
# Python
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        ans = 0
        temp = set()
        for num in nums:
            temp.add(num)
        for x in temp:
            if x - 1 in temp:
                continue
            y = x + 1
            while y in temp:
                y += 1
            ans = max(ans, y - x)
        return ans
rust 复制代码
// Rust
use std::collections::HashSet;
use std::cmp;

impl Solution {
    pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
        let mut temp = HashSet::new();
        for num in nums.iter() {
            temp.insert(num);
        }
        let mut ans = 0;
        for x in temp.iter() {
            if temp.contains(&(**x - 1)) {
                continue;
            }
            let mut y = **x + 1;
            while temp.contains(&y) {
                y += 1;
            }
            ans = cmp::max(ans, y - **x);
        }
        return ans;
    }
}
相关推荐
寻星探路7 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
你撅嘴真丑10 小时前
第九章-数字三角形
算法
在路上看风景10 小时前
19. 成员初始化列表和初始化对象
c++
uesowys10 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
zmzb010310 小时前
C++课后习题训练记录Day98
开发语言·c++
ValhallaCoder10 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮10 小时前
AI 视觉连载1:像素
算法
念风零壹10 小时前
C++ 内存避坑指南:如何用移动语义和智能指针解决“深拷贝”与“内存泄漏”
c++
智驱力人工智能10 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
猫头虎11 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven