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;
    }
};
相关推荐
肥猪猪爸11 分钟前
BP神经网络对时序数据进行分类
人工智能·深度学习·神经网络·算法·机器学习·分类·时序数据
dongzhenmao2 小时前
P1484 种树,特殊情形下的 WQS 二分转化。
数据结构·c++·windows·线性代数·算法·数学建模·动态规划
Dcs2 小时前
用不到 1000 行 Go 实现 BaaS,Pennybase 是怎么做到的?
java
Cyanto3 小时前
Spring注解IoC与JUnit整合实战
java·开发语言·spring·mybatis
qq_433888933 小时前
Junit多线程的坑
java·spring·junit
gadiaola3 小时前
【SSM面试篇】Spring、SpringMVC、SpringBoot、Mybatis高频八股汇总
java·spring boot·spring·面试·mybatis
写不出来就跑路3 小时前
WebClient与HTTPInterface远程调用对比
java·开发语言·后端·spring·springboot
Cyanto3 小时前
深入MyBatis:CRUD操作与高级查询实战
java·数据库·mybatis
麦兜*4 小时前
Spring Boot 集成Reactive Web 性能优化全栈技术方案,包含底层原理、压测方法论、参数调优
java·前端·spring boot·spring·spring cloud·性能优化·maven
thusloop4 小时前
380. O(1) 时间插入、删除和获取随机元素
数据结构·算法·leetcode