基础算法模板题(四)——双指针

双指针算法思想:
在这里插入图片描述
O(n^2)优化为O(n)

简单应用

输入为以空格分隔的单词
要求每个单词一行输出
在这里插入图片描述

最长连续不重复子序列

【题目描述】
在这里插入图片描述

AcWing 799. 最长连续不重复子序列

【思路】

import java.io.*;
import java.lang.Math;
class Main{
    static int N = 100010;
    public static void main(String args[]) throws Exception{
        BufferedReader bf= new BufferedReader(new InputStreamReader( System.in) );
        BufferedWriter log = new BufferedWriter(new OutputStreamWriter( System.out) );
        int n = Integer.parseInt(bf.readLine());
        int [] w =new int[N];
        String []strArr= bf.readLine().split(" ");
        for(int i = 0; i < n; i++) w[i] = Integer.parseInt(strArr[i]);
        int [] s = new int[N];
        int res =Integer.MIN_VALUE;
        for(int i = 0, j =0; i < n; i++){//枚举右端点
            s[ w[i] ]++;
            while(s[w[i]] > 1){//区间[j,i]出现重复元素
                s[w[j]] --; //剔除左端点元素
                j ++;
            }
            res = Math.max(res, i - j + 1);
        }
        log.write(res+" ");
        log.flush();
        bf.close();
        log.close();
    }
}

1240. 完全二叉树的权值

1240. 完全二叉树的权值

【误区】认为完全二叉树就是满二叉树
在这里插入图片描述

在这里插入图片描述

import java.util.Scanner;
class Main{
    static int N = 100010;
    static long s [] =  new long[N];
    public static void main(String args[]) {
        Scanner reader = new Scanner(System.in);
        int n = reader.nextInt();
        for(int i = 1; i <= n; i ++) {
            s[i] = s[i - 1] + reader.nextInt();
        }
        //  Math.log(n + 1) / Math.log(2) ==>以二为底的对数
        int h = (int)(Math.log(n) / Math.log(2) + 1) ; // 完全二叉树层数
        int l = 0;
        int r = 0;
        int index = 1;
        long res = 0;
        for(int i = 1; i <= h; i ++) {
            // 区间[l + 1, r]
            l = r;
            //r = r + (int)Math.pow(2, (i - 1));  // 2^n 不是2的n次方
            if( i == h) {
                r = n;
            }else{
                /*
                  Attention:左移运算优先级低于加减,要使用括号!!
                  且 2<<0等于2而不是1
                 */
                r = r + (int)Math.pow(2, (i - 1));
            }
            long ans = s[r] - s[l];
            if(ans > res){
                res = ans;
                index = i;
            }
        }
        // 最后一层
        System.out.println(index);
        
    }
    
}

双指针做法
在这里插入图片描述

import java.util.Scanner;
class Main{
    static int N = 200010;
    static long s [] =  new long[N];
    public static void main(String args[]) {
        Scanner reader = new Scanner(System.in);
        int n = reader.nextInt();
        for(int i = 1; i <= n; i ++) {
            s[i] = reader.nextInt();
        }
        long ans = 0;
        int index = 1;
        for(int d = 1, i = 1; i <= n ; d ++, i*= 2) {
            // i为序列最左端点
            long res = 0;
            // 第 d层的节点数最多为2^(d - 1)
            for(int j = i; j < i + Math.pow(2, d - 1); j ++) {
                res += s[j];
            }
            if(res > ans){
                ans = res;
                index = d;
            }
        }
        System.out.println(index);
        
    }
    
}

KMP

AcWing 831. KMP字符串(算法基础课)

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
class Main{
    static int N;
    public static void main(String args[]) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
        int n = Integer.parseInt(br.readLine());
        char[] p = br.readLine().toCharArray(); // n 个
        //System.out.println(n + " " + p.length);
        int m = Integer.parseInt(br.readLine());
        char[] s = br.readLine().toCharArray(); //m 个
        //System.out.println(m + " " + s.length);
        for(int i = 0, j = 0; i < m; i ++){
            
            int t = i;
            while( j < n && t < m && p[j] == s[t]) {
                j ++;
                t ++;
            }
            if(j == n) {
                System.out.print(i + " ");
            }
            j = 0;
        }
        
    }
}[

数组元素的目标和

【题目描述】

AcWing 800. 数组元素的目标和

解法一 、二分

【思路】
由于A、B序列是严格升序的,可以使用二分查找所需元素是否在序列中。
a + b = x
for(A中的每一个数a )
b = x -a
二分查找b是否在B序列中

import java.util.Scanner;
public class Main{
    static int  N = 100010;
    static int A[] = new int[N];
    static int B[] = new int[N];
    
    public static int binary_search(int x, int n){
        int l = 0, r = n - 1;
        while(l < r){
            int mid = (l + r) >> 1;
            if( B[mid] < x) l = mid + 1;
            else r = mid;
        }
        if( B[l] == x) return l;
        return -1;
    }
    public static void  main(String args[]){
        Scanner reader = new Scanner(System.in);
        int m = reader.nextInt(), n = reader.nextInt(), x = reader.nextInt();
        for(int i = 0; i < m; i ++) A[i] = reader.nextInt();
        for(int i = 0; i < n; i ++) B[i] = reader.nextInt();
        
        for(int i = 0; i < m; i ++){
            int b = x - A[i];
            int index = binary_search(b, n);
            if(  index != -1 ) 
                System.out.println(i + " "+index );
        }
    }
}

解法二 、双指针

【思路】
双指针的一般步骤是先暴力枚举思考,再从问题单调性出发,看看能不能改用双指针。
在这里插入图片描述

朴素做法:
for( a序列中的每个数 a[i])
    for(b序列中的每个数 b[j])
        if( a[i] + b[j] == target) 
        {
            输出(i,j) 
            break
        }
i指向a序列头部 j指向b序列尾部
i枚举a序列中的每个数 
for(int i = 0, j = m - 1; i < n; i ++){
    //寻找使得a[i] + b[j] <= x的第一个j的位置
    while( j >= 0 && a[i] + b[j] > x) j --;
    if( a[i] + b[j] == x){
        System.out.println(i + " "+ j);
        break;
    }
    
}
/*
朴素做法:
for( a序列中的每个数 a[i])
    for(b序列中的每个数 b[j])
        if( a[i] + b[j] == target) 
        {
            输出(i,j) 
            break
        }
i指向a序列头部 j指向b序列尾部
i枚举a序列中的每个数 
for(int i = 0, j = m - 1; i < n; i ++){  // 注意初始化条件 j = m - 1        
    //寻找使得a[i] + b[j] <= x的第一个j的位置
    while( j >= 0 && a[i] + b[j] > x) j --;
    if( a[i] + b[j] == x){
        System.out.println(i + " "+ j);
        break;
    }
    
}

*/

import java.util.Scanner;
class Main{
    static int N = 100010;
    static int a[] = new int[N];
    static int b[] = new int[N];
    public static void main(String args[]){
        Scanner reader = new Scanner(System.in);
        int n =  reader.nextInt(), m = reader.nextInt(), x = reader.nextInt();
        for(int i = 0; i < n; i ++) a[i] = reader.nextInt();
        for(int j = 0; j < m; j ++) b[j] = reader.nextInt();
        
        for(int i = 0, j = m - 1; i < n; i ++){
            //寻找使得a[i] + b[j] <= x的第一个j的位置
            while( j >= 0 && a[i] + b[j] > x) j --;
            if( a[i] + b[j] == x){
                System.out.println(i + " "+ j);
                break; //如果有多组解 不应该break,但题目说了有唯一解,所以可以提前break
            }
        
        }
    }
}

判断子序列

【题目描述】
在这里插入图片描述

AcWing 2816. 判断子序列

写法一

【思路】
枚举每一个a[i],查看b序列中是否有与之匹配的。若没有则j++,直至找到或者j出界。
若有匹配的则记录已经匹配的个数,同时i、j指针向前 。

伪代码

int len  = 0;
for( a[i])
    for(b[j])
    while( j < m - 1 && b[j] != a[i] ) j ++;
    //j指针向后移动
    if( a[i] == b[j]){
        len ++;
        j = j + 1;
    }
if( len == n) System.out.println("Yes");
else  System.out.println("No");

import java.util.Scanner;
public class Main{
    static int N = 100010;
    static int a[] = new int[N];
    static int b[] = new int[N];
    public static void main(String args[]){
        Scanner reader = new Scanner(System.in);
        int n = reader.nextInt(), m = reader.nextInt();
        for(int i = 0; i < n; i ++) a[i] = reader.nextInt();
        for(int i = 0; i < m; i ++) b[i] = reader.nextInt();
        
        int len = 0;
        for(int i = 0, j = 0; i < n; i++)
        {
            while( j < m - 1 && a[i] != b[j]) j ++;
            if(a[i] == b[j]) {
                j = j + 1;
                len ++;
            }
        }
        if( len == n) System.out.println("Yes");
        else  System.out.println("No");
    }
}

写法二

看到一个更简便的解法: z林深时见鹿 题解
思路是:i、j分别指向b、a序列,j指针只有a[j]和b[i]匹配上才移动,而i一直往前移动直至最后遍历完。这样如果b是a的子序列那么j最后一定会为n。

import java.util.Scanner;
public class Main{
    static int N = 100010;
    static int a[] = new int[N];
    static int b[] = new int[N];
    public static void main(String args[]){
        Scanner reader = new Scanner(System.in);
        int n = reader.nextInt(), m = reader.nextInt();
        for(int i = 0; i < n; i ++) a[i] = reader.nextInt();
        for(int i = 0; i < m; i ++) b[i] = reader.nextInt();
        
        int j = 0;
        for(int i = 0; i < m; i ++)
        {
            if( j < n && b[i] == a[j]) j ++;
        }
        if( j == n) System.out.println("Yes");
        else  System.out.println("No");
    }
}

4405. 统计子矩阵

在这里插入图片描述

import java.util.*;
import java.io.*;

class Main{
    static int N = 510;
    static int f[][] = new int [N][N];
    static int sum[][] = new int[N][N];
    public static void main(String args[]) throws Exception{
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str[] = bf.readLine().split(" ");
        int n = Integer.parseInt(str[0]), m = Integer.parseInt(str[1]), k = Integer.parseInt(str[2]);
        for(int i = 1; i <= n; i ++){
            String row[] = bf.readLine().split(" ");
            for(int j = 1; j <= m; j ++){
                f[i][j] = Integer.parseInt(row[j - 1]);
                sum[i][j] = sum[i - 1][j] + sum[i][j - 1] -sum[i - 1][j - 1] + f[i][j];
            }
        }
        // 枚举子矩阵,个数可能超过int
        long ans = 0;
        for(int i = 1; i <= m; i ++){
            for(int j = i; j <= m; j ++){
                // 固定左右边界i和j
                // 快慢指针s和t
                for(int s= 1, t = 1; t <= n; t ++){
                    //(s,i) (s, j)
                    //(t,i) (t, j)
                    while(s <= t && (sum[t][j] + sum[s - 1][i - 1] - sum[s - 1][j] - sum[t][i - 1]) > k){ // 不满足约束条件,慢指针向快指针移动
                        s ++;
                    }
                    if(s <= t){ // 注意包括等于,因为子矩阵可以是一个数
                        // 以s为上边界,t为下边界,且宽度为j - i + 1的子矩阵有t-s+1个
                        ans += (t - s + 1);
                    }
                }
            }
        }
        System.out.println(ans);
        
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值