AcWing算法基础课---第一讲基础算法---04双指针

双指针模板

for (int i = 0, j = 0; i < n; i ++ )
{
    while (j < i && check(i, j)) j ++ ;

    // 具体问题的逻辑
}

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

#include <iostream>

using namespace std;

const int N = 100010;

int n;
int a[N], s[N];

int main()
{
    cin >> n;
    for (int i = 0; i < n; i ++) cin >> a[i];
    
    int res;
    
    for (int i = 0, j = 0; i < n; i ++)
    {
        s[a[i]] ++; //记录i指针经过的数
        
        while (s[a[i]] > 1) //当此时i指针指向的数出现次数大于1,即有重复
        {
            s[a[j]] --;
            j ++; //弹出j指向的数并往前走一步
        }
        
        res = max(res, i - j + 2);
    }
    
    cout << res << endl;
    
    return 0;
}

AcWing 800. 数组元素的目标和

#include <iostream>

using namespace std;

const int N = 100010;

int n, m, x;
int a[N], b[N];

int main()
{
    cin >> n >> m >> x;
    
    for (int i = 0; i < n; i ++) cin >> a[i];
    for (int i = 0; i < m; i ++) cin >> b[i];
    
    for (int i = 0, j = m - 1; i < n; i ++)
    {
        while (j >= 0 && a[i] + b[j] > x) j --;
        if (a[i] + b[j] == x){
            cout << i << " " << j;
        }
    }
    
    return 0;
}

AcWing 2816. 判断子序列

#include <iostream>

using namespace std;

const int N = 100010;

int a[N], b[N];

int main()
{
    int n, m;
    cin >> n >> m;
    
    for (int i = 0; i < n; i ++) cin >> a[i];
    for (int i = 0; i < m; i ++) cin >> b[i];
    
    int i = 0, j = 0;
    while (i < n && j < m)
    {
        if (a[i] == b[j]) i ++; //当匹配时i往前
        j ++; //无论匹配与否j都往前
    }
    
    if (i == n) puts("Yes");
    else puts("No");
    
    
    return 0;
}
posted @   hjy94wo  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示