【LeetCode】第 293 场周赛题解

182 阅读1分钟

5234. 移除字母异位词后的结果数组

字符串

class Solution {
public:
    vector<string> removeAnagrams(vector<string>& words) {
        vector<string> res;
        res.push_back(words[0]);
        int n = words.size();
        for(int i=1; i<n; i++){
            vector<int> a(26), b(26);
           for(auto c : words[i-1]) a[c-'a']++;
           for(auto c : words[i]) b[c-'a']++;
           for(int k=0; k<26; k++) {
               if(a[k] != b[k]){
                   res.push_back(words[i]);
                   break;
               }
           }
        }
        return res;
    }
};

6064. 不含特殊楼层的最大连续楼层数

排序

class Solution {
public:
    int maxConsecutive(int bottom, int top, vector<int>& special) {
        sort(special.begin(), special.end());
        int n = special.size();
        int res = max(special[0] - bottom, top - special[n-1]);
        for(int i=1; i<n; i++){
            res = max(res, special[i] - special[i-1]-1);
        }
        return res;
    }
};

6065. 按位与结果大于零的最长组合

与操作都为 1 才是 1,int 是由 32 位组成,所有的数字二进制位置的为1的统计出来, 再求 32 位中最大的值,即为结果。

class Solution {
public:
    int largestCombination(vector<int>& candidates) {
        vector<int> f(32);
        int res = 0;
        for(auto c : candidates){
            for(int i=0; i<32; i++){
                if((c>>i)&1){
                    f[i]++;
                }
            }
        }
        for(int i=0; i<32; i++){
            res = max(res, f[i]);
        }
        return res;
    }
};

6066. 统计区间中的整数数目

区间合并

class CountIntervals {
public:
   map<int, int> mp;
   int res = 0;
    CountIntervals() {

    }
    
    void add(int left, int right) {
        auto it = mp.upper_bound(left);
        if(it != mp.begin()){
            it--;
        }
        while(it != mp.end()){
            // 与前一个区间没有交集, 找下一个区间
            if(it->second < left){
                it++; 
                continue;
            }
            // 与后一个区间没有交集
            if(right < it->first){
                break;
            }
            // 有交集的情况
            left = min(left, it->first);
            right = max(right, it->second);
            // 减去当前区间的数据
            res -= it->second - it->first+1;
            // 删除当前迭代, 返回下一个迭代的位置
            it = mp.erase(it);
        }
        // 添加合并后的区间
        mp.insert({left, right});
        // 加上新区间的数据
        res += right - left + 1;
    }
    
    int count() {
        return res;
    }
};

/**
 * Your CountIntervals object will be instantiated and called as such:
 * CountIntervals* obj = new CountIntervals();
 * obj->add(left,right);
 * int param_2 = obj->count();
 */