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;
    }
};
相关推荐
J2虾虾13 分钟前
Java使用jcifs读取Windows的共享文件
java·开发语言·windows
羊小猪~~18 分钟前
LLM--微调(Adapters,Prompt,Prefix)
算法·ai·大模型·llm·prompt·adapters·prefix
未来之窗软件服务24 分钟前
SenseVoicecpp ggml-hexagon.cpp大模型[AI人工智能(七十九)]—东方仙盟
人工智能·算法·仙盟创梦ide·东方仙盟
xiaoye-duck25 分钟前
《算法题讲解指南:动态规划算法--子数组系列》--25.单词拆分,26.环绕字符串中唯一的子字符串
c++·算法·动态规划
Fcy64829 分钟前
算法基础详解(二)枚举算法——普通枚举与二进制枚举
算法·枚举算法
Java成神之路-42 分钟前
Spring IOC 注解开发实战:从环境搭建到纯注解配置详解(Spring系列3)
java·后端·spring
承渊政道44 分钟前
【优选算法】(实战:栈、队列、优先级队列高频考题通关全解)
数据结构·c++·笔记·学习·算法·leetcode·宽度优先
py有趣1 小时前
力扣热门100题之将有序数组转为二叉搜索树
算法·leetcode
天若有情6731 小时前
Python精神折磨系列(完整11集·无断层版)
数据库·python·算法
凌波粒1 小时前
LeetCode--383.赎金信(哈希表)
java·算法·leetcode·散列表