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;
    }
}
相关推荐
君义_noip26 分钟前
信息学奥赛一本通 1524:旅游航道
c++·算法·图论·信息学奥赛
烁34734 分钟前
每日一题(小白)动态规划篇5
算法·动态规划
独好紫罗兰36 分钟前
洛谷题单2-P5717 【深基3.习8】三角形分类-python-流程图重构
开发语言·python·算法
滴答滴答嗒嗒滴42 分钟前
Python小练习系列 Vol.8:组合总和(回溯 + 剪枝 + 去重)
python·算法·剪枝
lidashent1 小时前
数据结构和算法——汉诺塔问题
数据结构·算法
小王努力学编程1 小时前
动态规划学习——背包问题
开发语言·c++·学习·算法·动态规划
f狐0狸x3 小时前
【蓝桥杯每日一题】4.1
c语言·c++·算法·蓝桥杯
ん贤3 小时前
2023第十四届蓝桥杯大赛软件赛省赛C/C++ 大学 B 组(真题&题解)(C++/Java题解)
java·c语言·数据结构·c++·算法·蓝桥杯
梭七y3 小时前
【力扣hot100题】(022)反转链表
算法·leetcode·链表
威视锐科技6 小时前
软件定义无线电36
网络·网络协议·算法·fpga开发·架构·信息与通信