leetcode热题100刷题计划

题目3

无重复字符的最长子串

思路

滑动窗口,设定当前窗口左侧为i,右侧为right,当到达右侧边界时,记录长度,

然后删掉最左侧的字符,即i+1;right则继续向后搜。

代码

public int lengthOfLongestSubstring(String s) {
        // 哈希集合,记录每个字符是否出现过
        Set<Character> occ = new HashSet<Character>();
        int n = s.length();
        // 右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动
        int rk = -1, ans = 0;
        for (int i = 0; i < n; ++i) {
            if (i != 0) {
                // 左指针向右移动一格,移除一个字符
                occ.remove(s.charAt(i - 1));
            }
            while (rk + 1 < n && !occ.contains(s.charAt(rk + 1))) {
                // 不断地移动右指针
                occ.add(s.charAt(rk + 1));
                ++rk;
            }
            // 第 i 到 rk 个字符是一个极长的无重复字符子串
            ans = Math.max(ans, rk - i + 1);
        }
        return ans;
    }

题目128

最长连续序列

思路

  1. 先把序列遍历到set当中
  2. 设以k为起点的序列,如果有k+1,k+2存在,则直接长度响应增加。
  3. 为了防止重复记录,如果有k-1存在,则条件2必然满足;所以只有在k-1不存在时,才会去执行2条件

代码

public int longestConsecutive(int[] nums) {
            Set<Integer> numset=new HashSet<Integer>();
            for(int num:nums){
                numset.add(num);
            }

            int longestStreak=0;
            for(int num:nums){
                if(!numset.contains(num-1)){
                    int current=num;
                    int curlength=1;
                    while(numset.contains(current+1)){
                        current++;
                        curlength++;
                    }
                    longestStreak=Math.max(longestStreak,curlength);
                }

            }
        return longestStreak;
    }

题目102

二叉树的层次遍历

思路

使用队列。同层结点会一起输出。每次循环时,把队列里的所有元素出队并且把各自的孩子结点进队,如此这般就是一层一层的层次遍历。

代码

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result=new LinkedList<>();
        Queue<TreeNode> queue=new LinkedList<>();

        if(root==null){
                return result;
        }
        queue.add(root);
        
        while(!queue.isEmpty()){
            int size=queue.size();
            List<Integer> temp=new LinkedList<>();
            //全部出队,保证这层全部输出
            while(size>0){
                TreeNode t=queue.poll();
                temp.add(t.val);
            if(t.left!=null)queue.add(t.left);
            if(t.right!=null)queue.add(t.right);
            size--;
            }
            
            result.add(temp);
        }

        return result;
    }
}
相关推荐
IT猿手9 分钟前
2025高维多目标优化:基于导航变量的多目标粒子群优化算法(NMOPSO)的无人机三维路径规划,MATLAB代码
开发语言·人工智能·算法·机器学习·matlab·无人机·cocos2d
阿乾之铭23 分钟前
动态规划算法
算法·动态规划
菠菠萝宝25 分钟前
【代码随想录】第九章-动态规划(上)
算法·动态规划·01背包·完全背包·多重背包·上楼梯
DTDanteDong27 分钟前
从头再来!社招找工作——算法题复习九:动态规划
算法·动态规划
Coco_926431 分钟前
Hot100 动态规划
算法·动态规划
卑微的小鬼40 分钟前
golang的var ,make ,new, := 的区别
算法
01_1 小时前
力扣hot100 ——和为k的子数组 前后缀和(积)各种情况总结
数据结构·算法·leetcode·前后缀和(积)计算
一只码代码的章鱼1 小时前
数据结构与算法-搜索-双向搜索 和 A*算法(字串变换,八数码,第k短路)
算法
咚咚轩2 小时前
算法1-2 排序(快排)
算法
楼台的春风2 小时前
【STM32 基于PID的闭环电机控制系统】
c语言·stm32·单片机·嵌入式硬件·mcu·物联网·算法