[二分法]leetcode1170:比较字符串最小字母出现频次(easy)

题目:
在这里插入图片描述
题解:

  • 使用二分法模板二,首先遍历words统计最小字母出现的频率,然后将频率表进行排序,遍历二分查找。最后在遍历queries,使用二分法在频率表寻找大于queries中单词最小频率的最小值,然后添加个数即可。

代码如下:

class Solution {
public:
    vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {
        vector<int> count;//统计words中最小字母出现的频率,然后排序后,便于二分查找
        for(auto& text:words){
            count.push_back(f(text));
        }
        sort(count.begin(),count.end());
        vector<int> res;
        for(auto& text:queries){
            int times=f(text);
            //二分法:寻找大于q[i]的最小字母频率的最小值
            int left=0,right=count.size();
            while(left<right){
                int mid=left+((right-left)>>1);
                if(count[mid]>times)right=mid;
                else left=mid+1;
            }
            //找到大于q[i]的最小字母频率的最小值的位置,返回包括它在内的大于times的个数
            if(left!=count.size())res.push_back(count.size()-left);
            //没有找到,则添加0
            else res.push_back(0);
        }
        return res;
    }

    //统计最小字符的个数
    int f(string& text){
        sort(text.begin(),text.end());
        int count=0;
        char ch=text[0];
        for(auto t:text)if(t==ch)count++;
        return count;
    }
};
发布了512 篇原创文章 · 获赞 175 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/qq_43152052/article/details/104129473