两个指针和滑动窗口模式
双指针和滑动窗口模式
模式 1:常量窗口(如 window = 4 或某个整数值)
例如,给定一个 (-ve 和 +ve) 整数数组,找到大小为 k.
的连续窗口的最大总和模式 2:(可变窗口大小)具有 的最大子数组/子字符串示例:总和
- 方法:
- 蛮力: 生成所有可能的子数组并选择最大长度的子数组 sum
- 最佳/最佳: 利用两个指针和滑动窗口将时间复杂度降低到O(n)
模式 3: 的子数组/子字符串的数量就像 sum=k。
这个问题很难解决,因为何时扩展(右++)或何时收缩(左++)变得很困难。
这个问题可以用模式2
解决
用于解决诸如查找 sum =k 的子串数量之类的问题。
-
这可以分解为
- 查找 sum 的子数组
- 查找 sum
模式4:找到最短/最小窗口
模式 2 的不同方法:
示例:总和
的最大子数组
public class Sample{ public static void main(String args[]){ n = 10; int arr[] = new int[n]; //Brute force approach for finding the longest subarray with sum <=k //tc : O(n^2) int maxlen=0; for(int i =0;i<arr.length;i++){ int sum =0; for(int j = i+1;j<arr.length;j++){ sum+=arr[j]; if(sum<=k){ maxLen = Integer.max(maxLen, j-i+1); } else if(sum > k) break; /// optimization if the sum is greater than the k, what is the point in going forward? } }
使用两个指针和滑动窗口的更好方法
//O(n+n) in the worst case r will move from 0 to n and in the worst case left will move from 0 0 n as well so 2n int left = 0; int right =0; int sum = 0; int maxLen = 0; while(right<arr.length){ sum+=arr[right]; while(sum > k){ sum = sum-arr[left]; left++; } if(sum <=k){ maxLen = Integer.max(maxLen, right-left+1); //if asked to print max subarray length,we print maxLen else asked for printing the subarray keep track of // left and right in a different variable } right++; }
最佳方法:
我们知道,如果找到子数组,我们将其长度存储在 maxLen 中,但是在添加 arr[right] 时,如果总和大于 k,那么当前我们通过执行 sum = sum-arr[left] 和 left++ 来向左收缩。
我们知道当前的最大长度是maxLen,如果我们继续缩小左索引,我们可能会得到另一个满足条件(<=k)的子数组,但长度可能小于当前的maxLen,那么我们不会更新maxLen,直到我们找到另一个满足条件并且也具有 len > 的子数组。 maxLen,则仅更新 maxLen。
当子数组不满足条件 (<=k)int left = 0 时,最佳方法是仅在子数组长度大于 maxLen 时收缩左侧。
int right =0; int sum = 0; int maxLen = 0; while(right<arr.length){ sum+=arr[right]; if(sum > k){// this will ensure that the left is incremented one by one (not till the sum<=k because this might reduce the length i.e right-left+1 which will not be taken into consideration) sum = sum-arr[left]; left++; } if(sum <=k){ maxLen = Integer.max(maxLen, right-left+1); //if asked to print max subarray length,we print maxLen else asked for printing the subarray keep track of // left and right in a different variable } right++; } } }
以上是两个指针和滑动窗口模式的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

公司安全软件导致部分应用无法正常运行的排查与解决方法许多公司为了保障内部网络安全,会部署安全软件。...

将姓名转换为数字以实现排序的解决方案在许多应用场景中,用户可能需要在群组中进行排序,尤其是在一个用...

系统对接中的字段映射处理在进行系统对接时,常常会遇到一个棘手的问题:如何将A系统的接口字段有效地映�...

在使用IntelliJIDEAUltimate版本启动Spring...

在使用MyBatis-Plus或其他ORM框架进行数据库操作时,经常需要根据实体类的属性名构造查询条件。如果每次都手动...

Java对象与数组的转换:深入探讨强制类型转换的风险与正确方法很多Java初学者会遇到将一个对象转换成数组的�...

电商平台SKU和SPU表设计详解本文将探讨电商平台中SKU和SPU的数据库设计问题,特别是如何处理用户自定义销售属...

Redis缓存方案如何实现产品排行榜列表的需求?在开发过程中,我们常常需要处理排行榜的需求,例如展示一个�...
