博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
双指针
阅读量:3951 次
发布时间:2019-05-24

本文共 2505 字,大约阅读时间需要 8 分钟。

思路:
LeetCode第11题

双指针有两种思路:

一种是两边往中间靠,另一种是两个指针一快一慢,从起点出发,当满足条件时

慢指针尝试接近快指针缩小范围获得最优解

在这里插入图片描述

class Solution {    public int maxArea(int[] height) {        int begin = 0;        int end = height.length-1;        int res = 0;        while(begin

下面也是两指针往中间靠的例子:

class Solution {    public int trap(int[] height) {                int res=0,left=0,recordLeft=0,right=height.length-1,recordRight=0;                        while(left
recordLeft) { recordLeft = height[left]; }else{ res+= recordLeft- height[left];//如果当前位置高度比前面记录的高度小,该地是一个坑,可以形成积水 } left++; }else{ if(height[right]>recordRight) { recordRight = height[right]; }else{ res+=recordRight - height[right]; } right--; } } return res; }}

在这里插入图片描述

很明显这是一个快慢指针的问题了,这里用了一个count变量来计数,另count等于 shortChars的长度,右边指针扫到shortChars的一个字母并且是第一次扫到,count数量减一,当count数量为0的时候说明【left,right】区间包含了整一个shortChars 这时尝试去移动 left指针,缩小区间去尝试获得最优解,此时当left扫过shortChars 的字母的时候,count的数量就要加1了,当count数量不为一的时候又要去移动right 指针去寻找解区间

当然网上另一种是另count=0,当right扫过shortChars 时count+1

class Solution {    public String minWindow(String s, String t) {        char[] longChars = s.toCharArray();        char[] shortChars = t.toCharArray();        int [] map = new int[128];        int left=0,flagLeft=0;        int right=0,flagRight=0;        int count = shortChars.length;        int minLen = Integer.MAX_VALUE;                        for(char c:shortChars)        {            map[c]++;        }                        while(right
0) { count--; } map[longChars[right]]--; right++; while(count==0) { if(right-left
0) { count++; } left++; } } return minLen == Integer.MAX_VALUE ?"":s.substring(flagLeft,flagRight); }}

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。

由于java写这个代码不舒服,这里用一下C++ 的代码

class Solution {public:    int lengthOfLongestSubstring(string s) {                int freq[256] ={0};        int left=0;        int right=-1;        int res = 0;                while(left

总结一下快慢指针(滑动窗口的思想)

在这里插入图片描述

转载地址:http://tbyzi.baihongyu.com/

你可能感兴趣的文章
Android 加速度传感器 (G-Sensor) 收
查看>>
Linux 下如何 做patch 和打patch
查看>>
device_driver结构体
查看>>
模拟是本土仪表技术落后的原因之一
查看>>
锂电池驱动分析
查看>>
Android电源管理
查看>>
Android电源管理机制分析(zz)
查看>>
kobject与sysfs
查看>>
sysfs 文件系统
查看>>
Linux 内核/sys 文件系统之sysfs 属性文件
查看>>
Google_android_JNI使用方法
查看>>
Android JNI
查看>>
ARM与嵌入式linux如何入门
查看>>
git命令入门
查看>>
PreferenceActivity 全接触
查看>>
Android之PreferenceActivity
查看>>
在Ubuntu上搭建嵌入式Linux开发环境
查看>>
C语言数据类型:联合(union)
查看>>
记录每次更新到仓库
查看>>
PXA270嵌入式系统设计一:电源管理部分收藏
查看>>