[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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
发布了179 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40691051/article/details/104466807