leetcode【周赛】【442场】

Q2. 属性图 中等
给你一个二维整数数组 properties,其维度为 n x m,以及一个整数 k。
定义一个函数 intersect(a, b),它返回数组 a 和 b 中 共有的不同整数的数量 。
构造一个 无向图,其中每个索引 i 对应 properties[i]。如果且仅当 intersect(properties[i], properties[j]) >= k(其中 i 和 j 的范围为 [0, n - 1] 且 i != j),节点 i 和节点 j 之间有一条边。
返回结果图中 连通分量 的数量。

无向图连通性判断,下面代码过不去性能测试,测试用例通过665/668

待改进中

#include"iostream"
#include"vector"
#include "unordered_map"
#include "unordered_set"
#include"queue"
using namespace std;


 class Solution {
    public:
        int intersect(vector<int>& a, vector<int>& b) {
            unordered_set<int> set1(a.begin(), a.end());
            unordered_set<int> set2(b.begin(), b.end());
            int count = 0;
            for (const int& i : set2) {
                if (set1.count(i)) {
                    count++;
                }
            }
            return count;
        }
        int numberOfComponents(vector<vector<int>>& properties, int k) {
            //unordered_map<int, vector<int>> map;
            vector<vector<int>> flagNum(properties.size());
            vector<int> visit(properties.size(),false);
            for (int i = 0; i < properties.size(); i++) {
                for (int j = i+1; j < properties.size(); j++) {
                    int count = intersect(properties[i], properties[j]);
                    if (count >= k) {
                        flagNum[i].emplace_back(j);
                        flagNum[j].emplace_back(i);
                    } 
                }
            }
            int part = 0;
            queue<vector<int>> q;
    
            for (int i = 0; i < properties.size(); i++) {
                if (!visit[i]) {
                    q.push(flagNum[i]);
                    part++;
                    visit[i] = true;
                }
                while (!q.empty()) {
                    vector<int> nums = q.front();
                    q.pop();
                    for(int& num : nums) {
                        if(!visit[num]) {
                            q.push(flagNum[num]);
                            visit[num] = true;
                        }
                    }
                }
            }
            return part;
        }
    };


int main(int argc, char const *argv[])
{
    /* code */
    vector<vector<int>> num{{1,2,3},{2,3,4},{4,3,5}};
    Solution s;
    s.numberOfComponents(num,2);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值