128. 最长连续序列

思路:

剪枝: 判断当前元素是否有前一位元素(是否起始点)

哈希: 插入哈希集合,查询元素

总体: 起始点,从头向前,更新最高长度

语法注意:

(1)HashSetcontains 方法期望引用 &T 而不是值类型 T,主要是为了避免不必要的内存拷贝和移动,同时遵循 Rust 的所有权和借用规则

(2)在 for num in & HashSet 比在 for &num in &Vec 中遍历 快 20 倍。

  • 遍历对象不同HashSet 遍历(for num in &set)避免了重复元素和解引用操作,而 Vec 遍历(for &num in &nums)可能包含重复元素和解引用开销。

  • 性能差异HashSet 提供更高效的查找和避免重复计算,因此在大数据集上,遍历 HashSet 通常更快。

代码:

复制代码
use std::collections::*;

impl Solution {
    pub fn longest_consecutive(nums: Vec<i32>) -> i32 {
        let mut set = HashSet::new();
        for &num in &nums {
            set.insert(num);
        }
        let mut longest = 0;
        for num in &set {
            if set.contains(&(*num - 1)) {continue;}
            let mut temp = *num + 1;
            while set.contains(&(temp)) {
                temp += 1;
            }
            longest = longest.max(temp - *num);
            
        }
        longest
    }
}
相关推荐
得物技术9 小时前
得物推荐系统诊断 Agent:从 “调接口” 到 “会思考”|AICon 演讲整理
人工智能·算法·架构
Lugas9 小时前
为啥说男生找对象尽量在25岁前找到?
算法
MrZhao4009 小时前
从能跑到可用:一个 Agent Harness 还差哪些工程闭环?
算法
QN1幻化引擎9 小时前
Gravity-Anchored Cognitive Field Architecture: The DalinX V8/V10 Implementation
java·前端·算法
学计算机的计算基10 小时前
LeetCode 图论四题精讲:BFS、拓扑排序、Trie 树的模板与优化
java·笔记·算法
浩瀚地学10 小时前
【面试算法笔记】0202-链表-基本功能实现
java·经验分享·笔记·算法·面试
tkevinjd10 小时前
416分割等和子集
java·python·算法·leetcode·职场和发展
Keven_1110 小时前
算法札记:Tarjan与拓扑序(Topo)的关系
算法·拓扑·tarjan
ShallWeL10 小时前
AUC、F1、召回率怎么选
人工智能·算法·机器学习
水龙吟啸11 小时前
华为2026.6.3机考选择题+编程题【速刷敲黑板】
人工智能·深度学习·算法·华为