leetcode每日一题——Split With Minimum Sum

文章目录

一、题目

2578. Split With Minimum Sum

Given a positive integer num, split it into two non-negative integers num1 and num2 such that:

The concatenation of num1 and num2 is a permutation of num.

In other words, the sum of the number of occurrences of each digit in num1 and num2 is equal to the number of occurrences of that digit in num.

num1 and num2 can contain leading zeros.

Return the minimum possible sum of num1 and num2.

Notes:

It is guaranteed that num does not contain any leading zeros.

The order of occurrence of the digits in num1 and num2 may differ from the order of occurrence of num.

Example 1:

Input: num = 4325

Output: 59

Explanation: We can split 4325 so that num1 is 24 and num2 is 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum.

Example 2:

Input: num = 687

Output: 75

Explanation: We can split 687 so that num1 is 68 and num2 is 7, which would give an optimal sum of 75.

Constraints:

10 <= num <= 109

二、题解

我的麻烦解法

cpp 复制代码
class Solution {
public:
    int splitNum(int num) {
        vector<int> vals;
        while(num){
            vals.push_back(num % 10);
            num /= 10;
        }
        sort(vals.begin(),vals.end(),greater<int>());
        int a = 0,b = 0;
        int oddCount = 0,evenCount = 0;
        for(int i = 0;i < vals.size();i++){
            if(i % 2 == 0){
                if(oddCount == 0) a += vals[i];
                else a += pow(10,oddCount) * vals[i];
                oddCount++;
            }
            else{
                if(evenCount == 0) b += vals[i];
                else b += pow(10,evenCount) * vals[i];
                evenCount++;
            }
        }
        return a + b;
    }
};

更好的解法

得到num1和num2时从最高位开始乘更好,不要像我上面那样从个位开始乘

cpp 复制代码
class Solution {
public:
    int splitNum(int num) {
        string stnum = to_string(num);
        sort(stnum.begin(), stnum.end());
        int num1 = 0, num2 = 0;
        for (int i = 0; i < stnum.size(); ++i) {
            if (i % 2 == 0) {
                num1 = num1 * 10 + (stnum[i] - '0');
            }
            else {
                num2 = num2 * 10 + (stnum[i] - '0');
            }
        }
        return num1 + num2;
    }
};
相关推荐
IT乐手9 分钟前
Java 实现异步转同步的方法
java
杨杨杨大侠9 分钟前
附录 1:🚀 Maven Central 发布完整指南:从零到成功部署
java·github·maven
一碗白开水一26 分钟前
【第19话:定位建图】SLAM点云配准之3D-3D ICP(Iterative Closest Point)方法详解
人工智能·算法
编码浪子28 分钟前
趣味学RUST基础篇(函数式编程闭包)
开发语言·算法·rust
渣哥31 分钟前
Java HashMap 扩容机制详解:触发条件与实现原理
java
赵星星52031 分钟前
Spring Bean线程安全陷阱:90%程序员都会踩的坑,你中招了吗?
java
Want5951 小时前
C/C++圣诞树②
c语言·c++·算法
得物技术1 小时前
0基础带你精通Java对象序列化--以Hessian为例|得物技术
java·后端·编程语言
橘子在努力1 小时前
【橘子SpringCloud】OpenFegin源码分析
java·spring boot·spring·spring cloud
我是廖志伟1 小时前
JVM新生代Eden区域深度解析
java·jvm·memory management