Leetcode 第 293 场周赛题解

Problem A - 移除字母异位词后的结果数组

解法:模拟

按题意模拟即可。

参考代码(c++)

class Solution {
public:
    vector<string> removeAnagrams(vector<string>& words) {
        vector<string> ans;
        ans.push_back(words[0]);
        for (int i = 1; i < words.size(); i++) {
            vector<int> A(26), B(26);
            for (char c : words[i - 1]) A[c - 'a']++;
            for (char c : words[i]) B[c - 'a']++;
            for (int j = 0; j < 26; j++) if (A[j] != B[j]) { ans.push_back(words[i]); break; }
        }
        return ans;
    }
};
Problem B - 不含特殊楼层的最大连续楼层数
解法:排序
我们把 bottom - 1 和 top + 1 也看作特殊楼层加入 special 中,然后将 special 排序。答案就是 special 中相邻元素之差的最大值减一。

参考代码(c++)
class Solution {
public:
    int maxConsecutive(int bottom, int top, vector<int>& special) {
        special.push_back(bottom - 1);
        special.push_back(top + 1);
        sort(special.begin(), special.end());
        int ans = 0;
        for (int i = 1; i < special.size(); i++) ans = max(ans, special[i] - special[i - 1] - 1);
        return ans;
    }
};
Problem C - 按位与结果大于零的最长组合
解法:枚举
我们枚举按位与的结果哪一位不是零,那么这一位不是零的所有数都可以参与按位与。选择最多数参与的那一位作为答案即可。复杂度 \mathcal{O}(n \log A)O(nlogA),其中 AA 是 candidates 中的最大值。

参考代码(c++)
class Solution {
public:
    int largestCombination(vector<int>& candidates) {
        int ans = 0;
        for (int i = 0; i <= 30; i++) {
            int t = 0;
            for (int x : candidates) if (x >> i & 1) t++;
            ans = max(ans, t);
        }
        return ans;
    }
};
Problem D - 统计区间中的整数数目
解法:模拟
求区间并集模板题。用一个 set 有序地维护所有不相交的区间,当加入区间 [left, right] 时,通过 lower_bound 快速找到第一个右端点大等于 left - 1 的区间,然后不断用接下来的区间和 [left, right] 合并,直到当前区间的左端点大于 right + 1。由于每个区间只会加入以及离开 set 一次,复杂度 \mathcal{O}(n \log n)O(nlogn)。

参考代码(c++)
class CountIntervals {
    typedef pair<int, int> pii;

    int ans = 0;
    set<pii> st;

public:
    CountIntervals() {
    }
    
    void add(int left, int right) {
        int L = left, R = right;
        auto it = st.lower_bound(pii(left - 1, -2e9));
        while (it != st.end()) {
            if (it->second > right + 1) break;
            L = min(L, it->second);
            R = max(R, it->first);
            ans -= it->first - it->second + 1;
            st.erase(it++);
        }
        ans += R - L + 1;
        st.insert(pii(R, L));
    }
    
    int count() {
        return ans;
    }
};

/**
 * Your CountIntervals object will be instantiated and called as such:
 * CountIntervals* obj = new CountIntervals();
 * obj->add(left,right);
 * int param_2 = obj->count();
 */
如果本文对你有帮助,别忘记给我个3连 ,点赞,转发,评论,
咱们下期见。收藏 等于白嫖,点赞才是真情。






#面试##春招##笔试题目##面经##Java##前端##Python##C/C++#
全部评论
都是大神啊,我之前参加过牛客的比赛,哎一言难尽啊
点赞 回复 分享
发布于 2022-05-16 13:55

相关推荐

牛客60022193...:大厂都招前端,他们觉得AI能替代前端,可能他们公司吊打btaj吧
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务