Leetcode6267-添加边使所有节点度数都为偶数

4 篇文章 0 订阅

分类讨论:

因为每条边会连接两个点,所以总度数为偶数,那么度数为奇数的点的个数也一定为偶数。又因为最多连接两条边,所以度数为奇的点数可能的取值为:0、2、4。

主要是讨论在这三种情况的无解的情况是怎样的,即这些点直接连边的情况是怎样的即可。

class Solution {
public:
    bool isPossible(int n, vector<vector<int>>& e) {
        vector<int> deg(n,0);
        for(auto p:e){
            deg[p[0]-1]++;
            deg[p[1]-1]++;
        }
        int cnt=0;
        vector<int> g;
        unordered_set<int> st;
        for(int i=0;i<n;i++){
            if(deg[i]&1){
                cnt++;
                g.push_back(i);
                st.insert(i);
            }
        }
        if(cnt>4) return 0;
        for(auto c:g) if(deg[c]==n-1) return 0;
        vector<int> t(n,0);
        int z=0;
        for(auto p:e){
            int x=p[0]-1,y=p[1]-1;
            if(st.count(x)&&st.count(y)) z+=2;
        }
        if(z==6) return 0;
        return 1;
    }
};

时间复杂度:O(n+m)。

空间复杂度:O(n)。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值