LeetCode每日一题:786. 第 K 个最小的素数分数【2021/11/29】

153 阅读1分钟

题目链接:786. 第 K 个最小的素数分数 - 力扣(LeetCode) (leetcode-cn.com)

难度:Hard

分式 x1y1\frac{x1}{y1}x2y2\frac{x2}{y2} 比较十,可以转换为 x1y2x1*y2x2y1x2*y1 比较,通过自定义排序,直接返回第 kk 个即可。

class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        vector<int> ans;
        int len1 = s.size();
        int len2 = p.size();
        if(len2 > len1){
            return ans;
        }
        unordered_map<int,int>m1;
        unordered_map<int,int>m2;
        for(int i=0;i<len2;i++){
            m1[p[i]-'a']++;
            m2[s[i]-'a']++;
        }
        int l = 0,r = len2-1;
        while(r<len1){
            if(m1==m2){
                ans.push_back(l);
            }
            if(m2[s[l]-'a'] == 1){
                m2.erase(s[l]-'a');
            } else {
                m2[s[l]-'a']--;
            }
            l++;
            m2[s[++r]-'a']++;
        }
        return ans;
    }
};