双指针模型

 

 

 

 

 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

const int N = 1e6 + 10, M = 2010;

int n, m;
int a[N];
int st[M];
int ll, rr = 1e8;

int main() {
    scanf("%d%d", &n, &m);
    for(int i = 0; i < n; i ++ ) scanf("%d", &a[i]);
    
    int l = 0, r = -1, cnt = 0;
    for(; r ++ < n;) {
        if(st[a[r]] == 0) cnt ++ ;
        st[a[r]] ++ ;
        while(st[a[l]] > 1) {
            st[a[l]] -- ;
            l ++ ;
        }
        
        if(cnt >= m) {
            if(r - l < rr - ll) {
                rr = r, ll = l;
            }
        }
    }
    
    cout << ll + 1 << ' ' << rr + 1 << endl;

    return 0;
}

 

 

 

class Solution {
public:
    int expressiveWords(string s, vector<string>& words) {
        int n = s.size();
        int res = 0;

        auto check = [&](string &s, string &p) -> bool {
            int n1 = s.size(), n2 = p.size();

            int p1 = 0, p2 = 0;
            while(p1 < n1 && p2 < n2) {
                int cnt1 = 0, cnt2 = 0;
                char c = s[p1];

                while(p1 < n1 && s[p1] == c) p1 ++ , cnt1 ++ ;
                while(p2 < n2 && p[p2] == c) p2 ++ , cnt2 ++ ;

                if(cnt1 < cnt2 || (cnt1 > cnt2 && cnt1 < 3)) return 0;
            }

            return p1 == n1 && p2 == n2;
        };

        for(auto &word: words) {
            if(check(s, word)) res ++ ;
        }

        return res;
    }
};

 

 

 

class Solution {
public:
    int longestStrChain(vector<string>& words) {
        int n = words.size();

        sort(words.begin(), words.end(), [&](auto &a, auto &b) {
            return a.size() < b.size();
        });

        vector<int> f(n, 1);

        auto check = [&](string &a, string &b) -> bool {
            int n = a.size(), m = b.size();
            if(n >= m || m - n >= 2) return false;
            int i = 0, j = 0, cnt = 0;
            while(i < n && j < m) {
                if(a[i] == b[j]) i ++ ;
                else{
                    cnt ++ ;
                }
                j ++ ;
            }
            return cnt < 2;
        };

        for(int i = 0; i < n; i ++ ) {
            for(int j = 0; j < i; j ++ ) {
                if(check(words[j], words[i])) {
                    f[i] = max(f[i], f[j] + 1);
                }
            }
        }
        return *max_element(f.begin(), f.end());
    }
};

 

posted @ 2023-10-26 09:35  深渊之巅  阅读(3)  评论(0编辑  收藏  举报