返回顶部

LeetCode第 277 场周赛

5989. 元素计数

题目描述:给你一个数组nums,对于其中的元素x,若在数组中存在y , z,满足条件y < x < z,则称x是好的,统计数组中好数的数目。

思路:数据范围很小,直接暴力即可,要是数据范围过大,使用map等统计一下最大最小值即可,复杂度可以做到\(O(nlogn)\)

时间复杂度:\(O(nlogn)\)

参考代码:

class Solution {
public:
    int countElements(vector<int>& nums) {
        sort(nums.begin() ,nums.end());
        int res = nums.size();
        if(nums[0] == nums.back()) return 0;
        map<int, int>mp;
        for(auto num : nums) mp[num]++;
        res -= mp[nums[0]];
        res -= mp[nums.back()];
        return res;
    }
};

5991. 按符号重排数组

题目描述:给你一个正数和负数个一半的数组,将数组重排,使得正负相间并且不改变原来正负数的相对顺序。

思路:根据题意模拟即可。

时间复杂度:\(O(n)\)

参考代码:

class Solution {
public:
    vector<int> rearrangeArray(vector<int>& nums) {
        vector<int>neg , pos;
        for(auto num : nums){
            if(num < 0) neg.push_back(num);
            else pos.push_back(num);
        }
        int n = neg.size();
        vector<int>res;
        for(int i = 0 ; i < n ; ++i){
            res.push_back(pos[i]);
            res.push_back(neg[i]);
        }
        return res;
    }
};

5990. 找出数组中的所有孤独数字

题目描述:给你一个数组nums,若数组中的数字x只出现一次且x + 1 , x - 1不在数组中出现,则说这个数字是好的,统计数组中好数的数目。

思路:拿个map存储一下每个数字的出现次数然后再扫一遍统计答案即可。

时间复杂度:\(O(nlogn)\)

参考代码:

class Solution {
public:
    vector<int> findLonely(vector<int>& nums) {
        map<int , int>map;
        for(int num : nums) map[num]++;
        vector<int>res;
        for(int num : nums){
            if(map[num] > 1) continue;
            if(map.count(num - 1) == 0 && map.count(num + 1) == 0) res.push_back(num);
        }
        return res;
    }
};

5992. 基于陈述统计最多好人数

题目描述:给你一个\(n \times n\)二维数组statements,表示\(n\)个人的相互描述:

  • statements[i][j] = 1表示i认为j是好人
  • statements[i][j] = 0 表示i认为j是坏人
  • statements[i][j] = 2表示i没有对j做描述

好人说真话,坏人可能说真话可能说假话,问好人的最大可能数目。

数据范围:\(2 \leq n \leq 15\)

思路:考虑到数据范围比较小,可以暴力枚举所有可能的好人坏人情况,复杂度\(O(2^n)\),然后检验当前枚举的情况是否符合题意,复杂度\(O(n^2)\)。可以通过此题。

时间复杂度:\(O(2^n \times n^2)\)

参考代码:

class Solution {
public:
    int maximumGood(vector<vector<int>>& statements) {
        
        int n = statements.size();
        vector<int> path(n , 0);
        int res = 0;
        auto check = [&]()->bool{
            for(int i = 0 ; i < n ; ++i){
                if(path[i] == 0) continue;
                for(int j = 0 ; j < n ; ++j){
                    if(i == j) continue;
                    if(path[j] == 0 && statements[i][j] == 1) return false;
                    if(path[j] == 1 && statements[i][j] == 0) return false;
                }
            }
            return true;
        };
        auto dfs = [&](auto dfs , int cur, int idx)->void{
            if(idx == n){
                if(check()) res = max(res , cur);
                return ;
            }
            path[idx] = 0;
            dfs(dfs , cur, idx + 1);
            path[idx] = 1;
            dfs(dfs , cur + 1, idx + 1);
        };
        dfs(dfs , 0 , 0);
        return res;
    }
};
posted @ 2022-01-23 12:12  cherish-lgb  阅读(25)  评论(0编辑  收藏  举报