[Dichotomy] leetcode1170: Minimum letters appear string comparison frequency (Easy)

Title:
Here Insert Picture Description
Solution:

  • Use dichotomy template Second, the statistical frequency words first traverse the smallest letter that appears, then the frequency table is sorted, traversing the binary search. Finally traversal queries, using dichotomy find the minimum frequency is greater than the minimum value of the word queries in the frequency table, and then add the number to.

code show as below:

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;
    }
};
Published 512 original articles · won praise 175 · views 120 000 +

Guess you like

Origin blog.csdn.net/qq_43152052/article/details/104129473