1363. Largest Multiple of Three/数学

题目描述

Given an integer array of digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order.

Since the answer may not fit in an integer data type, return the answer as a string.

If there is no answer return an empty string.

Example 1:

Input: digits = [8,1,9]
Output: "981"

Example 2:

Input: digits = [8,6,7,1,0]
Output: "8760"

Example 3:

Input: digits = [1]
Output: ""

Example 4:

Input: digits = [0,0,0,0,0,0]
Output: "0"

Constraints:

  • 1 <= digits.length <= 10^4
  • 0 <= digits[i] <= 9
  • The returning answer must not contain unnecessary leading zeros.

分析

能被3整除的数各位数的和sum必能被3整除,反之也成立。因此,计算各位之和,计算res=sum%3,若res!=0,删掉最小的数使其满足。容易忽视一点:若res == 1,不仅可以删掉一个除3余1的数,也可以删掉两个除3余2的数。对于res == 2也是如此。

AC代码

这里模仿的评论区的一位大神的思路写的:

class Solution {
    int cnt[10]={0},sum=0;
public:
    bool Delete(int n){
        for(int i=n;i<=9;i+=3) if(cnt[i]>0) {cnt[i]--;return 1;}
        return 0;
    }
    string largestMultipleOfThree(vector<int>& digits) {
        string ans;
        for(int k:digits) {sum+=k;cnt[k]++;}
        if(sum%3==1) if(!Delete(1)) Delete(2),Delete(2);
        if(sum%3==2) if(!Delete(2)) Delete(1),Delete(1);
        for(int i=9;i>=0;i--) while(cnt[i]--) ans+=i+'0';
        if(ans.size()>0&&ans[0]=='0') return "0";
        return ans;
    }
};

发布了123 篇原创文章 · 获赞 11 · 访问量 5549

猜你喜欢

转载自blog.csdn.net/weixin_43590232/article/details/104557791