秋招算法刷题8

20240422

2.两数相加

时间复杂度O(max(m,n)),空间复杂度O(1)

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head=null,tail=null;
        int carry=0;
        while(l1!=null||l2!=null){
            int n1=l1!=null?l1.val:0;
            int n2=l2!=null?l2.val:0;
            int sum=n1+n2+carry;
            if(head==null){
                head=tail=new ListNode(sum%10);
            }else{
                tail.next=new ListNode(sum%10);
                tail=tail.next;
            }
            carry=sum/10;
            if(l1!=null){
                l1=l1.next;
            }
            if(l2!=null){
                l2=l2.next;
            }

        }
        if(carry>0){
            tail.next=new ListNode(carry);
        }
        return head;
    }

19.删除链表的倒数第N个节点

1.计算链表长度
时间复杂度O(n)空间复杂度O(1)

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy=new ListNode(0,head);
        int length=getLength(head);
        ListNode cur=dummy;
        for(int i=1;i<length-n+1;++i){
            cur=cur.next;
        }
        cur.next=cur.next.next;
        ListNode ans=dummy.next;
        return ans;
    }
    public int getLength(ListNode head){
        int length=0;
        while(head!=null){
            ++length;
            head=head.next;
        }
        return length;
    }
}

2.双指针法
时间复杂度O(n)空间复杂度O(1)

public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy=new ListNode(0,head);
        ListNode first=head;
        ListNode second=dummy;
        for(int i=0;i<n;++i){
            first=first.next;
        }
        while(first!=null){
            first=first.next;
            second=second.next;
        }
        second.next=second.next.next;
        ListNode ans=dummy.next;
        return ans;
    }

24.俩两交换链表中的节点

1.递归
时间空间复杂度O(n)

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode newHead=head.next;
        head.next=swapPairs(newHead.next);
        newHead.next=head;
        return newHead;
    }
}

2.迭代
时间复杂度O(n),空间复杂度O(1)

public ListNode swapPairs(ListNode head) {
        ListNode dummyHead=new ListNode(0);
        dummyHead.next=head;
        ListNode temp=dummyHead;
        while(temp.next!=null&&temp.next.next!=null){
            ListNode node1=temp.next;
            ListNode node2=temp.next.next;
            temp.next=node2;
            node1.next=node2.next;
            node2.next=node1;
            temp=node1;
        }
        return dummyHead.next;
    }

20240423

138.随机链表的复制

1.回溯+哈希表
时间复杂度和空间复杂度O(n)

class Solution {
    Map<Node,Node> cacheNode=new HashMap<Node,Node>();
    public Node copyRandomList(Node head) {
        if(head==null){
            return null;
        }
        if(!cacheNode.containsKey(head)){
            Node headNew=new Node(head.val);
            cacheNode.put(head,headNew);
            headNew.next=copyRandomList(head.next);
            headNew.random=copyRandomList(head.random);
        }
        return cacheNode.get(head);
    }
}

2.迭代+节点拆分
时间O(n),空间O(1)

public Node copyRandomList(Node head) {
        if(head==null){
            return null;
        }
        for(Node node=head;node!=null;node=node.next.next){
            Node nodeNew=new Node(node.val);
            nodeNew.next=node.next;
            node.next=nodeNew;
        }
        for(Node node=head;node!=null;node=node.next.next){
            Node nodeNew=node.next;
            nodeNew.random=(node.random!=null)?node.random.next:null;

        }
        Node headNew=head.next;
        for(Node node=head;node!=null;node=node.next){
            Node nodeNew=node.next;
            node.next=node.next.next;
            nodeNew.next=(nodeNew.next!=null)?nodeNew.next.next:null;

        }
        return headNew;
    }

14.最长公共前缀

1.横向扫描

public String longestCommonPrefix(String[] strs) {
        if(strs==null||strs.length==0){
            return "";
        }
        String prefix=strs[0];
        int count=strs.length;
        for(int i=1;i<count;i++){
            prefix=longestCommonPrefix(prefix,strs[i]);
            if(prefix.length()==0){
                break;
            }
        }
        return prefix;
    }
    public String longestCommonPrefix(String str1,String str2){
        int length=Math.min(str1.length(),str2.length());
        int index=0;
        while(index<length&&str1.charAt(index)==str2.charAt(index)){
            index++;
        }
        return str1.substring(0,index);
    }
}

2.纵向扫描

public String longestCommonPrefix(String[] strs) {
       if(strs==null||strs.length==0){
            return "";
       }
       int length=strs[0].length();
       int count=strs.length;
       for(int i=0;i<length;i++){
            char c=strs[0].charAt(i);
            for(int j=1;j<count;j++){
                if(i==strs[j].length()||strs[j].charAt(i)!=c){
                    return strs[0].substring(0,i);
                }
            }
       }
       return strs[0];
    }

给定一个 n,算出 1 到 n 的最小公倍数

public static BigInteger f(int n)
    {
        int[] x = new int[n+1];

        for(int i=1; i<=n; i++) x[i] = i;

        for(int i=2; i<n; i++)
        {
            for(int j=i+1; j<=n; j++)
            {
                if(x[j] % x[i]==0)
                    x[j]=x[j]/x[i];
            }
        }
        //解决大数相乘
        BigInteger m = BigInteger.ONE;
        for(int i=2; i<=n; i++)
        {
            m = m.multiply(BigInteger.valueOf((long)x[i]));

        }

        return m;

    }

二叉树的前、中、后遍历

1.非递归

https://www.bilibili.com/video/BV1GY4y1u7b2/?spm_id_from=pageDriver&vd_source=4bff775c9c6da7af76663b10f157a21f

2.递归

https://blog.csdn.net/loss_rose777/article/details/131399871

5.最长回文子串

1.动态规划
时间复杂度、空间O(n^2)

public String longestPalindrome(String s) {
        int len=s.length();
        if(len<2){
            return s;
        }
        int maxLen=1;
        int begin=0;
        boolean[][] dp=new boolean[len][len];
        for(int i=0;i<len;i++){
            dp[i][i]=true;
        }
        char[] charArray=s.toCharArray();
        for(int L=2;L<=len;L++){
            for(int i=0;i<len;i++){
                int j=L+i-1;
                if(j>=len){
                    break;
                }
                if(charArray[i]!=charArray[j]){
                    dp[i][j]=false;
                }else{
                    if(j-i<3){
                        dp[i][j]=true;
                    }else{
                        dp[i][j]=dp[i+1][j-1];
                    }
                }
                if(dp[i][j]&&j-i+1>maxLen){
                    maxLen=j-i+1;
                    begin=i;
                }
            }
        }
        return s.substring(begin,begin+maxLen);
    
    }

2.中心扩展算法

class Solution {
    public String longestPalindrome(String s) {
        if(s==null||s.length()<1){
            return "";
        }
        int start=0,end=0;
        for(int i=0;i<s.length();i++){
            int len1=expandAroundCenter(s,i,i);
            int len2=expandAroundCenter(s,i,i+1);
            int len=Math.max(len1,len2);
            if(len>end-start){
                start=i-(len-1)/2;
                end=i+len/2;
            }
        }
            return s.substring(start,end+1);
        }

    
    public int expandAroundCenter(String s,int left,int right){
        while(left>=0&&right<s.length()&&s.charAt(left)==s.charAt(right)){
            --left;
            ++right;
        }
        return right-left-1;
    }
}

20.回文子串

class Solution {
    public int countSubstrings(String s) {
        if(s==null||s.length()==0){
            return 0;
        }
        int count=0;
        for(int i=0;i<s.length();++i){
            count+=countPalindrome(s,i,i);
            count+=countPalindrome(s,i,i+1);
        }
        return count;
    }
    private int countPalindrome(String s,int start,int end){
        int count=0;
        while(start>=0&&end<s.length()&&s.charAt(start)==s.charAt(end)){
            count++;
            start--;
            end++;
        }
        return count;
    }
}

605.种花问题

public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int count=0;
        int m=flowerbed.length;
        int prev=-1;
        for(int i=0;i<m;i++){
            if(flowerbed[i]==1){
                if(prev<0){
                    count+=i/2;
                }else{
                    count+=(i-prev-2)/2;
                }
                if(count>=n){
                    return true;
                }
                prev=i;
            }
        }
        if(prev<0){
            count+=(m+1)/2;
        }else{
            count+=(m-prev-1)/2;
        }
        return count>=n;
    }

20240426

136.只出现一次的数字

华为od面试题:我23年5月7日竟然写过这个题,但是我一年后面试时候还是不会。都不知道我是太笨了呢,还是没努力呢
(其余出现2次)

public int singleNumber(int[] nums) {
        int single=0;
        for(int num:nums){
            single^=num;
        }
        return single;
    }

137.只出现一次的数字(其余出现三次)

1.哈希表
时间空间都是O(n)

public int singleNumber(int[] nums) {
        Map<Integer,Integer> freq=new HashMap<Integer,Integer>();
        for(int num:nums){
            freq.put(num,freq.getOrDefault(num,0)+1);
        }
        int ans=0;
        for(Map.Entry<Integer,Integer> entry:freq.entrySet()){
            int num=entry.getKey(),occ=entry.getValue();
            if(occ==1){
                ans=num;
                break;
            }
        }
        return ans;
    }

2.遍历统计

public int singleNumber(int[] nums) {
        int[] counts=new int[32];
        for(int num:nums){
            for(int j=0;j<32;j++){
                counts[j]+=num&1;
                num>>>=1;
            }
        }
        int res=0,m=3;
        for(int i=0;i<32;i++){
            res<<=1;
            res|=counts[31-i]%m;
        }
        return res;
    }

260.只出现一次的数字III

1.哈希表

public static int singleNumber(int[] nums) {
        Map<Integer,Integer> freq=new HashMap<Integer,Integer>();
        for(int num:nums){
            //freq.put(num, freq.getOrDefault(num,0)+1);
            freq.put(num,freq.containsKey(num)?freq.get(num)+1:1);
           
        }
        int ans=0;
        for(Map.Entry<Integer,Integer> entry:freq.entrySet()){
            int num=entry.getKey(),occ=entry.getValue();
            if(occ==1){
                ans=num;
                break;
            }
        }
        return ans;
    }

2.位运算

public int[] singleNumber(int[] nums) {
        int xorsum=0;
        for(int num:nums){
            xorsum^=num;
        }
        int lowbit=xorsum&-xorsum;
        int[] ans=new int[2];
        for(int x:nums){
            ans[(x&lowbit)==0?0:1]^=x;
        }
        return ans;
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/593441.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Graph RAG:基于知识图谱的检索增强技术与优势对比

身处信息爆炸时代&#xff0c;如何从海量信息中获取准确全面的搜索结果&#xff0c;并以更直观、可读的方式呈现出来是大家期待达成的目标。传统的搜索增强技术受限于训练文本数量、质量等问题&#xff0c;对于复杂或多义词查询效果不佳&#xff0c;更无法满足 ChatGPT 等大语言…

【Linux】进程间通信 - 管道

文章目录 1. 进程间通信介绍1.1 进程间通信目的1.2 进程间通信发展1.3 进程间通信分类 2. 管道2.1 什么是管道2.2 匿名管道2.3 用 fork 来共享管道原理2.4 站在文件描述符角度 - 深入理解管道2.5 站在内核角度 - 管道本质2.6 管道读写规则2.7 管道特点 3. 命名管道3.1 匿名管道…

C语言实战项目--贪吃蛇

贪吃蛇是久负盛名的游戏之一&#xff0c;它也和俄罗斯⽅块&#xff0c;扫雷等游戏位列经典游戏的行列。在编程语言的教学中&#xff0c;我们以贪吃蛇为例&#xff0c;从设计到代码实现来提升大家的编程能⼒和逻辑能⼒。 在本篇讲解中&#xff0c;我们会看到很多陌生的知识&…

牛角源码 | 【独立版】商城盲盒源码带uniapp(H5+小程序+APP三端)全开源

前端uniapp开源代码&#xff0c;可用HBuilder工具无限发行H5、小程序和打包app&#xff0c;后端PHP开源源码&#xff0c;支持二开。 内有安装搭建教程&#xff0c;轻松部署&#xff0c;搭建即可运营&#xff0c;内置永久免费更新地址&#xff0c;后续无忧升级。 下载地址&…

window 安装ai 基础环境(yolo8,训练推理等)

安装步骤: 1. python sdk 3.9以上&#xff1a;选择 3.9.13, 不知道为什么 3.9.0-0a等安装pytorch 不行。 2. 显卡驱动 可以使用驱动精灵 直接安装N 卡推荐 3. 安装机器学习套件CUDA cuda 安装在PyTorch 需要根 PyTorch版本一致&#xff0c;我的 win-srv 最高支持 12.1 …

专业渗透测试 Phpsploit-Framework(PSF)框架软件小白入门教程(五)

本系列课程&#xff0c;将重点讲解Phpsploit-Framework框架软件的基础使用&#xff01; 本文章仅提供学习&#xff0c;切勿将其用于不法手段&#xff01; 继续接上一篇文章内容&#xff0c;讲述如何进行Phpsploit-Framework软件的基础使用和二次开发。 在下面的图片中&#…

星辰考古:TiDB v1.0 再回首

“ 1.0 版本只是个开始&#xff0c;是新的起点&#xff0c;愿我们一路相扶&#xff0c;不负远途。 前言 TiDB 是 PingCAP 公司自主设计、研发的开源分布式关系型数据库。 近日&#xff0c;TiDB v8.0.0 DMR 发布&#xff0c;详细发版说明戳这里&#xff1a; https://docs.pingca…

2024年Q1季度防晒霜数据分析:个性化与差异化成为破局关键

五一出游期间&#xff0c;防晒必不可少&#xff0c;尤其是随着“颜值经济”的崛起&#xff0c;防晒霜成为了许多消费者出游时的必备选择。但随着“物理防晒”、“硬防晒”等概念的推出&#xff0c;防晒霜作为“化学防晒”的代表&#xff0c;在今年Q1季度线上市场表现受到影响。…

ICode国际青少年编程竞赛- Python-1级训练场-变量入门

ICode国际青少年编程竞赛- Python-1级训练场-变量入门 1、 a 4 Dev.turnRight() Dev.step(a)2、 a 4 Spaceship.step(a) Dev.step(a)3、 a 4 Dev.step(a) Dev.turnLeft() Dev.step(a)4、 a 5 Dev.step(a) Spaceship.step(a) Dev.step(a)5、 a 3 Dev.step(a) Dev.tur…

轨道交通巡检机器人的应用范围

在现代轨道交通系统的庞大网络中&#xff0c;无数的轨道、设备和设施交织在一起&#xff0c;如同一个精密的机器在高效运转。而在这背后&#xff0c;轨道交通巡检机器人正悄然登场&#xff0c;它们如同一个个智能的守护者&#xff0c;穿梭于各个场景之中。那么&#xff0c;这些…

【LeetCode:1235. 规划兼职工作 + 动态规划 + 二分查找】

&#x1f680; 算法题 &#x1f680; &#x1f332; 算法刷题专栏 | 面试必备算法 | 面试高频算法 &#x1f340; &#x1f332; 越难的东西,越要努力坚持&#xff0c;因为它具有很高的价值&#xff0c;算法就是这样✨ &#x1f332; 作者简介&#xff1a;硕风和炜&#xff0c;…

win10安装DHCP服务--用于2台机器之间搭建简易网络来进入目标机器修改配置

前言&#xff1a; 客户多了&#xff0c;往往会出现各种突发情况。 比如一个客户现场没有DHCP&#xff0c;没有显示器&#xff0c;键盘。 你只有一台笔记本的情况下要配置目标机器的网络。要如何配置&#xff1f;&#xff1f; 这时候就可以使用这篇博客提供的方式了。 Windows…

Android使用kts发布aar到JitPack仓库

Android使用kts发布aar到JitPack 之前做过sdk开发&#xff0c;需要将仓库上传到maven、JitPack或JCenter,但是JCenter已停止维护&#xff0c;本文是讲解上传到JitPack的方式,使用KTS语法&#xff0c;记录使用过程中遇到的一些坑.相信Groovy的方式是大家经常使用的&#xff0c;…

Codeforces Round 738 (Div. 2) D2. Mocha and Diana (Hard Version)

题目 思路&#xff1a; 性质1&#xff1a;能在结点u&#xff0c;v添加边的充要条件是u&#xff0c;v在第一个图和第二个图都不连通 性质2&#xff1a;可以添加的边数等于 n - 1 - max(m1, m2)&#xff0c;并且添加边的顺序不会影响结果&#xff08;即 边&#xff08;u&#x…

U.S. Student Information Center——全球学历认证

权威机构 中国留服中心认证&#xff0c;全称是中国教育部留学服务中心国(境)外学历学位认证。国&#xff08;境&#xff09;外学历学位认证工作旨在落实中华人民共和国的留学政策&#xff0c;即中国教育部留学服务中心根据归国留学生提出的申请&#xff0c;鉴别国(境)外学历的…

C语言——文件相关操作

2.什么是文件 3.文件的打开和关闭 4.文件的顺序读写 5.文件的随机读写 6.文本文件和二进制文件 7.文件读取结束的判定 8.文件缓冲区 一、文件相关介绍 1、为什么使用文件 文件用于永久存储数据。通过使用文件&#xff0c;我们可以在程序关闭后保存数据&#xff0c;以便将来…

XBoot:基于Spring Boot 2.x的一站式前后端分离快速开发平台

XBoot&#xff1a;基于Spring Boot 2.x的一站式前后端分离快速开发平台 摘要 随着信息技术的迅速发展&#xff0c;快速构建高质量、高可靠性的企业级应用成为了迫切需求。XBoot&#xff0c;作为一个基于Spring Boot 2.x的一站式前后端分离快速开发平台&#xff0c;通过整合微信…

AI-数学-高中56-成对数据统计-线性回归方程

原作者视频&#xff1a;【成对数据统计】【一数辞典】1线性回归方程_哔哩哔哩_bilibili 注意&#xff1a;高中只学线性回归。 最小二乘法&#xff08;残差和平方最小的直线、方差最小>拟合程度最好&#xff09;&#xff1a;

滑动验证码登陆测试编程示例

一、背景及原理 处理登录时的滑动验证码有两个难点&#xff0c;第一个是找到滑块需要移动的距离&#xff0c;第二个是模拟人手工拖动的轨迹。模拟轨迹在要求不是很严的情况下可以用先加速再减速拖动的方法&#xff0c;即路程的前半段加速度为正值&#xff0c;后半段为负值去模…

微搭低代码入门03页面管理

目录 1 创建页面2 页面布局3 页面跳转总结 上一篇我们介绍了应用的基本操作&#xff0c;掌握了应用的概念后接着我们需要掌握页面的常见操作。 1 创建页面 打开应用的编辑器&#xff0c;在顶部导航条点击创建页面图标 在创建页面的时候可以从空白新建&#xff0c;也可以使用模…
最新文章