算法练习02——双指针

目录

  • 283. 移动零
  • 11. 盛最多水的容器
  • 15. 三数之和
  • 42. 接雨水*(暴力,双指针优化暴力,单调栈)
  • 27. 移除元素
  • 344. 反转字符串
  • 54. 替换数字(第八期模拟笔试)
  • 151. 反转字符串中的单词
  • 206. 反转链表
  • 19. 删除链表的倒数第 N 个结点.
  • 面试题 02.07. 链表相交
  • 142. 环形链表 II

283. 移动零

https://leetcode.cn/problems/move-zeroes/

class Solution {//方法一:简单覆盖//非零的从下标0添加,数组剩下位置都填0// public void moveZeroes(int[] nums) {//     int len=nums.length;//     int k=0;//     for(int i=0;i<len;i++){//         if(nums[i]!=0){//             nums[k++]=nums[i];//         }//     }//     while(k<len){//         nums[k++]=0;//     }// }//方法二:双指针//解释一下:如果数组没有0,那么快慢指针始终指向同一个位置,每个位置自己和自己交换;//如果数组有0,快指针先走一步,此时慢指针对应的就是0,所以要交换。public void moveZeroes(int[] nums) {int len=nums.length;int left=0;int right=0;while(right<len){if(nums[right]!=0){int temp = nums[left];nums[left] = nums[right];nums[right] = temp;left++;}right++;}}
}

11. 盛最多水的容器

https://leetcode.cn/problems/container-with-most-water/

class Solution {public int maxArea(int[] height) {//若向内 移动短板 ,水槽可能变大,因此下个水槽的面积 可能增大 。//若向内 移动长板 ,下个水槽的面积 可能会变小(或者不变) int left=0;int right=height.length-1;int res=0;while(left<right){int area= Math.min(height[left],height[right])*(right-left);res=Math.max(res,area);if(height[right]>=height[left]){left++;}else{right--;}}return res;}
}

15. 三数之和

https://leetcode.cn/problems/3sum/

class Solution {public List<List<Integer>> threeSum(int[] nums) {int len=nums.length;Arrays.sort(nums);//先排序List<List<Integer>> res=new ArrayList<>();for(int i=0;i<len;i++){if(nums[i]>0){return res;}if(i>0 && nums[i]==nums[i-1]){continue;//去重}int left=i+1;int right=len-1;while(right>left){int sum=nums[i]+nums[left]+nums[right];if(sum<0){left++;}else if(sum>0){right--;}else{res.add(Arrays.asList(nums[i],nums[left],nums[right]));left++;right--;while(right>left && nums[left]==nums[left-1]){left++;}while(right>left && nums[right]==nums[right+1]){right--;}}}}return res;}
}

42. 接雨水*(暴力,双指针优化暴力,单调栈)

https://leetcode.cn/problems/trapping-rain-water/

class Solution {public int trap(int[] height) {//3.单调栈int len=height.length;if (len <= 2) return 0;int res=0;Stack<Integer> s=new Stack<>();s.push(0);for(int i=1;i<len;i++){int top=s.peek();if(height[top]>height[i]){s.push(i);}else if(height[top]>height[i]){s.pop();s.push(i);}else{int curHigh=height[i];//目前节点的高度while(!s.isEmpty() && (curHigh>height[s.peek()])){int mid=s.pop();if(!s.isEmpty()){int left=s.peek();int h=Math.min(height[left],curHigh)-height[mid];int w=i-left-1;int area=h*w;if(area>0){res+=area;}}}s.push(i);}}return res;//2.双指针/*为了得到两边的最高高度,使用了双指针来遍历,每到一个柱子都向两边遍历一遍,这其实是有重复计算的。我们把每一个位置的左边最高高度记录在一个数组上(maxLeft[])右边最高高度记录在一个数组上(maxRight[]),这样就避免了重复计算。*/int len=height.length;if (len <= 2) return 0;int res=0;int maxLeft[]=new int[len];int maxRight[]=new int[len];// 记录每个柱子左边柱子最大高度maxLeft[0]=height[0];for(int i=1;i<len;i++){maxLeft[i]=Math.max(maxLeft[i-1],height[i]);}// 记录每个柱子右边柱子最大高度maxRight[len-1]=height[len-1];for(int i=len-2;i>=0;i--){maxRight[i]=Math.max(maxRight[i+1],height[i]);}for(int i=0;i<len;i++){if(i==0 || i==len-1){continue;}int h=Math.min(maxLeft[i],maxRight[i])-height[i];res+=h;}return res;//1.暴力解法//每一列雨水的高度,取决于该列左侧最高的柱子和右侧最高的柱子中最矮的//那个柱子的高度减去当前列的高度h=Math.min(maxLeft,maxRight)-height[i]int len=height.length;int res=0;for(int i=0;i<len;i++){if(i==0 || i==len-1){continue;}int maxLeft=0;int maxRight=0;for(int j=i;j<len;j++){maxRight=Math.max(maxRight,height[j]);}for(int j=i;j>=0;j--){maxLeft=Math.max(maxLeft,height[j]);}int h=Math.min(maxLeft,maxRight)-height[i];res+=h;}return res;}
}

27. 移除元素

https://leetcode.cn/problems/remove-element/description/

class Solution {public int removeElement(int[] nums, int val) {//1.快慢指针int slow=0;for(int fast=0;fast<nums.length;fast++){if(nums[fast]!=val){nums[slow++]=nums[fast];}}return slow;//2.相向双指针int leftIndex = 0;int rightIndex = nums.length - 1;while (leftIndex <= rightIndex) {// 找左边等于val的元素while (leftIndex <= rightIndex && nums[leftIndex] != val){++leftIndex;}// 找右边不等于val的元素while (leftIndex <= rightIndex && nums[rightIndex] == val) {-- rightIndex;}// 将右边不等于val的元素覆盖左边等于val的元素if (leftIndex < rightIndex) {nums[leftIndex++] = nums[rightIndex--];}}return leftIndex;   // leftIndex一定指向了最终数组末尾的下一个元素}
}

344. 反转字符串

https://leetcode.cn/problems/reverse-string/description/

class Solution {public void reverseString(char[] s) {int len=s.length;int left=0;int rigtht=len-1;while(left<rigtht){char t=s[left];s[left++]=s[rigtht];s[rigtht--]=t;}}
}

54. 替换数字(第八期模拟笔试)

https://kamacoder.com/problempage.php?pid=1064

import java.util.Scanner;class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);String s = in.nextLine();StringBuilder sb = new StringBuilder();for (int i = 0; i < s.length(); i++) {if (Character.isDigit(s.charAt(i))) {sb.append("number");}else sb.append(s.charAt(i));}System.out.println(sb);}
}

151. 反转字符串中的单词

https://leetcode.cn/problems/reverse-words-in-a-string/description/

class Solution {public String reverseWords(String s) {//去掉字符串中的多余空格StringBuilder sb=clearSpace(s);//对整个字符串进行翻转reverseAll(sb,0,sb.length()-1);//对每个单词进行翻转reverseStr(sb);return sb.toString();}//去掉字符串中的多余空格public StringBuilder clearSpace(String s){int len=s.length();int start=0;int end=len-1;while(s.charAt(start)==' ')start++;while(s.charAt(end)==' ')end--;StringBuilder sb=new StringBuilder();while(start<=end){char c=s.charAt(start);if(c!=' ' || sb.charAt(sb.length()-1)!=' '){sb.append(c);}start++;}return sb;}//对整个字符串进行翻转public void reverseAll(StringBuilder sb,int start,int end){while(start<end){char temp=sb.charAt(start);sb.setCharAt(start++,sb.charAt(end));sb.setCharAt(end--,temp);}}//对每个单词进行翻转public void reverseStr(StringBuilder sb){int start = 0;int end = 1;int n = sb.length();while (start < n) {while (end < n && sb.charAt(end) != ' ') {end++;}reverseAll(sb, start, end - 1);start = end + 1;end = start + 1;}}
}

206. 反转链表

https://leetcode.cn/problems/reverse-linked-list/description/

/*** Definition for singly-linked list.* public class ListNode {*     int val;*     ListNode next;*     ListNode() {}*     ListNode(int val) { this.val = val; }*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode reverseList(ListNode head) {ListNode cur=head;ListNode pre=null;ListNode temp=null;while(cur!=null){temp=cur.next;cur.next=pre;pre=cur;cur=temp;}return pre; }
}

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

https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/

/*** Definition for singly-linked list.* public class ListNode {*     int val;*     ListNode next;*     ListNode() {}*     ListNode(int val) { this.val = val; }*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode removeNthFromEnd(ListNode head, int n) {//2.双指针,快慢指针//如果要删除倒数第n个节点,让fast移动n步,然后让fast和slow同时移动,//fast和slow中间永远差n个节点,直到fast指向链表末尾。//删掉slow所指向的节点就可以了。ListNode preHead=new ListNode(0);preHead.next=head;ListNode slow=preHead;ListNode fast=preHead;while(n>0){fast=fast.next;n--;}fast=fast.next;while(fast!=null){fast=fast.next;slow=slow.next;}slow.next=slow.next.next;return preHead.next;//1.普通方法ListNode cur=head;int size=0;while(cur!=null){cur=cur.next;size++;}if(n==size){head=head.next;return head;}cur=head;for(int i=0;i<size-n-1;i++){cur=cur.next;}if(cur.next!=null)cur.next=cur.next.next;return head;}
}

面试题 02.07. 链表相交

https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/description/

交点不是数值相等,而是指针相等

/*** Definition for singly-linked list.* public class ListNode {*     int val;*     ListNode next;*     ListNode(int x) {*         val = x;*         next = null;*     }* }*/
public class Solution {public ListNode getIntersectionNode(ListNode headA, ListNode headB) {ListNode pA=headA;ListNode pB=headB;int lenA=0;int lenB=0;while(pA!=null){pA=pA.next;lenA++;}while(pB!=null){pB=pB.next;lenB++;}pA=headA;pB=headB;if(lenA>lenB){int gap=lenA-lenB;while(gap>0){pA=pA.next;gap--;}while(pA!=null){if(pA==pB){return pA;}pA=pA.next;pB=pB.next;}}else{int gap=lenB-lenA;while(gap>0){pB=pB.next;gap--;}while(pA!=null){if(pA==pB){return pA;}pA=pA.next;pB=pB.next;}}return null;}
}

142. 环形链表 II

https://leetcode.cn/problems/linked-list-cycle-ii/

/*** Definition for singly-linked list.* class ListNode {*     int val;*     ListNode next;*     ListNode(int x) {*         val = x;*         next = null;*     }* }*/
public class Solution {public ListNode detectCycle(ListNode head) {ListNode slow=head;ListNode fast=head;while(fast!=null && fast.next!=null){slow=slow.next;fast=fast.next.next;if(slow==fast){ListNode index01=head;ListNode index02=fast;while(index01!=index02){index01=index01.next;index02=index02.next;}return index01;}}return null;}
}

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Electron开发的十大神级产品,vscode、atom、skype、figma等

Hi、我是贝格前端工场&#xff0c;今天分享一下基于Electron的十大著名产品&#xff0c;欢迎友友们补充。 Visual Studio Code 这是一款由微软开发的轻量级代码编辑器&#xff0c;它提供了丰富的功能和插件生态系统&#xff0c;支持多种编程语言和开发工具。Visual Studio Cod…

SpringBoot整理-安全(Spring Security)

在 Spring Boot 应用中实现安全性通常涉及到集成 Spring Security 框架。Spring Security 是一个功能强大且高度可定制的认证和访问控制框架,非常适合用于保护 Spring Boot 应用。 核心特性 认证: 认证是确认某个实体的身份,Spring Security 支持多种认证机制,如表单登录、L…

C++ | 部分和函数partial_sum的使用技巧

如果你需要处理一个数组的前缀和&#xff0c;或者数组中某一段元素的前缀和&#xff0c;你会怎么做呢&#xff1f; partial_sum函数是STL中的函数&#xff0c;用于计算范围的部分和&#xff0c;并从结果开始分配范围中的每个元素&#xff0c;range[first,last)中相应元素的部分…

爬虫工作量由小到大的思维转变---<第四十章 Scrapy Redis 的Queue问题>

前言: 对于scrapy-redis有一个特殊的地方,就是队列的进出关系,因为我们的url请求会从各个任务统一归纳到redis里面,因此,如何解决下载请求这个问题,也是scrapy-redis的一个关键点!!! 正文: 先讲解代码,讲它自带的3个队列方式; 然后,再讲讲如何自定义队列... 原文翻译: 1.Bas…

<网络安全>《14 日志审计系统》

1 概念 日志审计系统是用于全面收集企业IT系统中常见的安全设备、网络设备、数据库、服务器、应用系统、主机等设备所产生的日志&#xff08;包括运行、告警、操作、消息、状态等&#xff09;并进行存储、监控、审计、分析、报警、响应和报告的系统。 日志审计系统是一种用于…

投资更好的管理会计系统,探索全面预算管理的奥秘

目前&#xff0c;我国财政体制正值如火如荼的调整阶段&#xff0c;各级政府和部门响应国家号召&#xff0c;旨在加强管理会计系统建设&#xff0c;制定具有先导性和科学性的现代化全面预算管理制度&#xff0c;从而将我国财力推向一个新高度。其中&#xff0c;基于服务或产品的…

工程师 - headless模式

headless 英文释义&#xff1a; 在没有用户界面的情况下运行&#xff1b;具体地说&#xff0c;在没有显示器、键盘和鼠标的情况下运行。 Running without a user interface; specifically, running without a monitor, keyboard, and mouse. 说明 所谓的“无头系统”&#x…

【PostgreSQL灵活使用psql执行SQL的一些方式】

一、psql执行SQL并使用选项灵活输出结果 可以不进入数据库&#xff0c;在命令行&#xff0c;使用psql 的-c选项跟上需要执行的SQL。来获取SQL的执行结果 postgresubuntu-linux-22-04-desktop:~$ psql -c "select 1,2" ?column? | ?column? -------------------…

Swift Vapor 教程(CURD 操作)

接上篇使用 Swift Vapor 对数据库进行简单的操作。 下面会使用一个稍微简单的方式进行 CURD 操作 import Fluent import Vaporstruct SongController: RouteCollection {func boot(routes: Vapor.RoutesBuilder) throws {let songs routes.grouped("songs")// GET…

tengine ngx_http_upstream_dynamic_module 动态域名解析功能的代码详细解析

tengine ngx_http_upstream_dynamic_module 动态域名解析功能的代码详细解析 1. 为什么需要域名动态解析2. 配置指令3. 加载模块3. 源码分析3.1 指令解析3.2 upstream负载均衡算法的初始化3.3 upstream负载均衡上下文的初始化3.4 获取upstream的服务器地址3.5 域名解析回调处理…

【Boost】:parser代码的基本结构(二)

parser代码的基本结构 一.总体概述二. EumeFile的实现三.ParserHtml的实现四.SaveHtml实现五.完整源代码 打开parser.cc,用vscode或者vim都行。 一.总体概述 首先递归式的把文件名和路径读入一个数组内&#xff0c;接着把数组内的每一个数据按照一定的格式进行划分&#xff0c;…

创建型模式-单例模式:定义、实现及应用

目录 一、模式定义二、针对问题1.解决的问题2.解决方案3.举个例子4.设计模式适合场景5.实现方式6.优缺点7.与其他模式的关系 三、代码实现 一、模式定义 单例模式&#xff08;Singleton Pattern&#xff09;是一种创建型模式&#xff0c;用于限制某个类只能创建一个对象。它提…

大数据信用报告查询费用一般要多少钱?

一些不少朋友在申贷的时候被拒贷之后&#xff0c;得到的原因就是因为大数据不良被拒&#xff0c;这时候很多人都反过来查询自己的大数据信用报告&#xff0c;而查询的价格也是不少朋友都比较关注的&#xff0c;那大数据信用报告查询费用一般要多少钱呢?下面本文就为你介绍一下…

码农也得“开口说话”

咱们程序员兄弟们有时候被大家贴上了“闷葫芦”的标签&#xff0c;好像我们只适合跟电脑谈恋爱&#xff0c;不爱搭理人似的。不过今儿咱要说的是&#xff0c;码农界的大神可不只是会敲代码那么简单&#xff0c;会聊天、懂合作那也是必不可少的生存法则&#xff01; 一、内向也…

vue3中如何实现图片的压缩

首先&#xff0c;为什么需要进行图片压缩&#xff1a; 减少页面加载时间&#xff1a;因为图片是页面中常见的资源之一&#xff0c;较大的图片会增加页面的加载时间&#xff0c;影响用户体验&#xff0c;压缩图片可以减小图片的文件大小&#xff0c;提升页面加载速度。节省网络…

App ICP备案获取iOS和Android的公钥和证书指纹

依照《工业和信息化部关于开展移动互联网应用程序备案工作的通知》&#xff0c;向iOS和安卓平台提交App时需要先提交ICP备案信息。 iOS平台&#xff1a; 1、下载appuploader工具&#xff1a;Appuploader home -- A tool improve ios develop efficiency such as submit ipa to…

vue yarn certificate has expired

背景&#xff1a;我在用ant design pro框架进行初始化时&#xff0c;安装脚手架时&#xff0c;安装yarn时显示报错 原因分析&#xff1a;查了很久的资料&#xff0c;这种情况应该是开了服务器代理访问导致ssl安全证书失效了 解决办法&#xff1a; 在终端输入&#xff1a;yarn…

【MybatisPlus篇】查询条件设置(范围匹配 | 模糊匹配 | 空判定 | 包含性判定 | 分组 | 排序)

文章目录 &#x1f384;环境准备⭐导入依赖⭐写入User类⭐配置启动类⭐创建UserDao 的 MyBatis Mapper 接口&#xff0c;用于定义数据库访问操作⭐创建配置文件&#x1f6f8;创建测试类MpATest.java &#x1f354;范围查询⭐eq⭐between⭐gt &#x1f354;模糊匹配⭐like &…

使用ngrok内网穿透

没有服务器和公网IP&#xff0c;想要其他人访问自己做好的网站&#xff0c;使用这款简单免费的内网穿透小工具——ngrok&#xff0c;有了它轻松让别人访问你的项目~ 一、下载ngrok 官网地址&#xff1a;ngrok | Unified Application Delivery Platform for Developers&#x…

Redis(十一)单线程VS多线程

文章目录 概述为何选择单线程主要性能瓶颈多线程特性和IO多路复用概述Unix网络编程中的五种IO模型Blocking IO-阻塞IONoneBlocking IO-非阻塞IOIO multiplexing-IO多路复用signal driven IO-信号驱动IOasynchronous IO-异步IO 场景&#xff1a;引出epoll总结 开启Redis多线程其…