[leetcode]5172. 形成三的最大倍数

在这里插入图片描述
在这里插入图片描述

定理:各位数之和能被3整除的数就是3的倍数

在这里插入图片描述
https://zhidao.baidu.com/question/987173910529894859.html

class Solution {
    int cnt[10] = {0};
    int sum = 0;
    int del(int m)
    {
        for(int i = m; i <= 9; i += 3)
        {
            if(cnt[i] > 0)
            {
                cnt[i]--;
                return 1;
            }
        }
        return 0;
    }
public:
    string largestMultipleOfThree(vector<int>& digits) {
        for(int x : digits)
        {
            cnt[x]++;
            sum += x;
        }
        if(cnt[0] == digits.size()) return "0";
        if(sum % 3 == 1)
        {
            if(!del(1))
            {
                del(2);
                del(2);
            }
        }
        else if(sum % 3 == 2)
        {
            if(!del(2))
            {
                del(1);
                del(1);
            }
        }
        string res;
        for(int i = 9; i >= 0; i--)
        {
            while(cnt[i]--)
            {
                res += i + '0';
            }
        }
        if(res.size() > 1 && res[0] == '0') return "0";
        return res;
    }
};

参考:

class Solution {
    int cnt[10],sum;
    string ans = "";
    int del(int m)
    {
        for(int i=m;i<=9;i+=3)if(cnt[i]){cnt[i]--;return 1;}
        return 0;
    }
public:
    string largestMultipleOfThree(vector<int>& d) {
        for(auto x:d)cnt[x]++,sum+=x;
        if(cnt[0]==d.size())return "0";
        if(sum%3==1)if(!del(1))del(2),del(2);
        if(sum%3==2)if(!del(2))del(1),del(1);
        for(int i=9;i>=0;i--)while(cnt[i]--)ans+=i+'0';
        //应该加上下面这句
        if(ans.size() > 1 && ans[0] == '0') return "0";
        return ans;
    }
};

作者:YusenZhang_chatc
链接:https://leetcode-cn.com/problems/largest-multiple-of-three/solution/c-qu-diao-zui-xiao-zhi-8ms-by-yusenzhang_chatc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值