力扣打卡——day01

128. 最长连续序列 - 力扣(LeetCode)

这道题目最开始大家想的肯定是sort,然后计数计算最长序列。但是要求时间复杂度为:o(n),就不能用sort 了。一般在leetcode中,对时间复杂度有要求,就用空间来换,对空间复杂度有要求,就用时间来换。

基于这种思路我们就想要求最长的,就是要记录下有没有相邻的元素,比如遍历到100这个元素,我们需要查看99, 101这两个元素在不在序列中,这样去更新最大长度。而记录元素有没有这个事我们太熟悉了,用set这种数据结构,而set这种数据结构是需要o(n)的空间来换取的,这就是我们刚才说的用空间来换时间。

复制代码
class Solution {
    public int longestConsecutive(int[] nums) {
        //使用空间复杂度进行换时间复杂度
        Set<Integer> numsSet=new HashSet<>();
        for(int num:nums){
            numsSet.add(num);
        }
        int longMax=0;
        for(int num: nums){
             int number=num;
            if(numsSet.remove(number)){
                int currtLength=1;
                //向左进行移动
                while(numsSet.remove(number-1)) number--;
                currtLength+=(num-number);

                //向右进行移动
                number=num;
                while(numsSet.remove(number+1)) number++;
                currtLength+=(number-num);
                //最后进行比较
                longMax= Math.max(currtLength,longMax);
            }
          
        }
        return longMax;
    }
}

283. 移动零 - 力扣(LeetCode)

思路: 使用双指针将非0的数据向前移动,末尾进行补零

复制代码
class Solution {
    public void moveZeroes(int[] nums) {
        //使用双指针就行
        int slow=0;

        //将非0的数据向前移动
        for(int fast=0;fast<nums.length;fast++){
            if(nums[fast]!=0){
                nums[slow++]=nums[fast];
            }
        }
        //末尾进行补零
        for(;slow<nums.length;slow++){
            nums[slow]=0;
        }
        
    }
}
相关推荐
karry_k7 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
karry_k7 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端
vibecoding日记8 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr213811 小时前
Verilog参数化游程编码RLE模块
算法
SamDeepThinking11 小时前
从源码到代码:MyBatis-Flex 与 MyBatis-Plus 的逐项对比
java·后端·程序员
望易11 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
她的男孩13 小时前
Spring Boot 接 Flowable 工作流:用 3 个注解搭一个请假审批流程
java·后端·架构
复杂网络15 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
荣码15 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python