滑动窗口

904水果成篮

思路:

  1. 用一个map来记录slowptr fastptr之间的水果种类和个数,用一个count记录slowptr fastptr之间的水果总数,用typeofFruit记录slowptr fastptr之间的水果种类
  2. fastptr不断向前,count不断++,map记录水果种类,当遇到不存在map中的水果,typeoffruit++
  3. 当种类>2时,slowptr开始向前,直到map中有一种水果变成0,种类回到2
  4. 记录水果数量
class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        int typeOfFruit=0;
        int count=0;
        int ans=1;
        int n=fruits.size();
        unordered_map<int,int> f;
        int slowptr=0,fastptr=0;
        for(;fastptr<n;fastptr++)
        {
            if(f[fruits[fastptr]]==0)
            {
                typeOfFruit++;
            }
            count++;
            f[fruits[fastptr]]++;
            while(typeOfFruit>2)
            {
                f[fruits[slowptr]]--;
                if(f[fruits[slowptr]]==0)
                {
                    typeOfFruit--;
                }
                count--;
                slowptr++;
            }
            ans=max(ans,count);
        }
        return ans;

    }
};

76最小覆盖字串

思路:

  1. 用一个hashtable记录t中所有字母的个数
  2. fastptr遍历hashtable
  • scnt记录s中各个元素出现的次数
    • 如果scnt元素少于tcnt的元素,说明当前字符满足构成最小字串的要求,用count++
    • slow指针指的元素在scnt中出现的次数<tcnt的次数,说明当前字符是重复的,把他从snt中--,slow++
    • 如果count==t.length()说明当前字串是能覆盖的,检查他是否是最小字串
class Solution {
public:
    string minWindow(string s, string t) {
        string ans;
        if(s==t)
        {
            return t;
        }
        if(s.length()<t.length())
        {
            return ans;
        }
        unordered_map<char,int> scnt,tcnt;
        for(int i=0;i<t.length();i++)
        {
            tcnt[t[i]]++;
        }
        int slowptr=0,fastptr=0;
        int count=0;
        for(;fastptr<s.length();fastptr++)
        {
            scnt[s[fastptr]]++;
            if(scnt[s[fastptr]]<=tcnt[s[fastptr]])
            {
                count++;
            }
            while(scnt[s[slowptr]]>tcnt[s[slowptr]])
            {
                scnt[s[slowptr]]--;
                slowptr++;
            }
            if(count==t.length())
            {
                if((fastptr-slowptr+1)<ans.length()||ans.empty())
                ans=s.substr(slowptr, fastptr-slowptr+1);
            }
        }
        return ans;

    }
};
posted @ 2024-01-12 10:40  LiviaYu  阅读(11)  评论(0)    收藏  举报