[LeetCode] 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
andnum2
is a permutation ofnum
.- In other words, the sum of the number of occurrences of each digit in
num1
andnum2
is equal to the number of occurrences of that digit innum
.
- In other words, the sum of the number of occurrences of each digit in
num1
andnum2
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
andnum2
may differ from the order of occurrence ofnum
.
Example 1:
num1 is
Example 2:
num1 num2
Constraints:
10 <= num <= 109
最小和分割。
给你一个正整数
num
,请你将它分割成两个非负整数num1
和num2
,满足:
num1
和num2
直接连起来,得到num
各数位的一个排列。
- 换句话说,
num1
和num2
中所有数字出现的次数之和等于num
中所有数字出现的次数。num1
和num2
可以包含前导 0 。请你返回
num1
和num2
可以得到的和的 最小 值。注意:
num
保证没有前导 0 。
num1
和num2
中数位顺序可以与num
中数位顺序不同。
思路是贪心。具体做法是把 num 先转换成一个 charArray,对其排序,然后遍历这个 charArray,将遍历到的每个 digit 分配到 num1 和 num2 中,以这种方式最后拼接出来的 num1 和 num2 才是最小的。
时间O(nlogn)
空间O(n)
Java实现
1 class Solution { 2 public int splitNum(int num) { 3 char[] nums = String.valueOf(num).toCharArray(); 4 Arrays.sort(nums); 5 int n = nums.length; 6 int num1 = 0; 7 int num2 = 0; 8 boolean flag = true; 9 for (int i = 0; i < n; i++) { 10 char cur = nums[i]; 11 if (flag) { 12 num1 = num1 * 10 + cur - '0'; 13 } else { 14 num2 = num2 * 10 + cur - '0'; 15 } 16 flag = !flag; 17 } 18 return num1 + num2; 19 } 20 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2019-10-09 [LeetCode] 128. Longest Consecutive Sequence
2019-10-09 [LeetCode] 203. Remove Linked List Elements
2019-10-09 [LeetCode] 334. Increasing Triplet Subsequence
2019-10-09 [LeetCode] 27. Remove Element
2019-10-09 [LeetCode] 7. Reverse Integer
2019-10-09 [LeetCode] 170. Two Sum III - Data structure design