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;
    }
}
相关推荐
战族狼魂25 分钟前
高频面试题精选:分治与AI Agent架构
人工智能·算法·大模型·大语言模型
李剑一30 分钟前
你用过网易的将军令嘛?它底层实现账号保护的原理相当简单粗暴
算法
Scott9999HH36 分钟前
告别流量波动玄学!从法拉第电磁定律到底层 C/C++ 流量累积算法,深度解密工业级电磁流量计选型与开发
c语言·c++·算法
香辣牛肉饭2 小时前
【算法】动态规划 最长公共子序列(LCS)
经验分享·笔记·算法·动态规划
.徐十三.3 小时前
一篇文章看到最短路径——Dijkstra算法
算法
科学实验家4 小时前
二叉树的几道题
算法
abcy0712135 小时前
flink state实例
大数据·算法·flink
qizayaoshuap5 小时前
# [特殊字符] 密码生成器 — 鸿蒙ArkTS安全算法与密码强度评估系统
java·算法·安全·华为·harmonyos
良木林5 小时前
滑动窗口 - LeetCode hot 100
javascript·算法·leetcode·双指针·滑动窗口