LeetCode题解——Create Maximum Number

该博客讨论了如何从两个数字数组中创建最大数字,保持数组内相对顺序不变。首先介绍了简单版本的贪心解决方案,然后解决当需要合并所有数字时的情况,最后提出完整解决方案,将两个部分的结果合并成最大数字。
摘要由CSDN通过智能技术生成

Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum number of length k <= m + n from digits of the two. The relative order of the digits from the same array must be preserved. Return an array of the k digits. You should try to optimize your time and space complexity.

Example 1:

nums1 = [3, 4, 6, 5]
nums2 = [9, 1, 2, 5, 8, 3]
k = 5
return [9, 8, 6, 5, 3]

Example 2:

nums1 = [6, 7]
nums2 = [6, 0, 4]
k = 5
return [6, 7, 6, 0, 4]

Example 3:

nums1 = [3, 9]
nums2 = [8, 9]
k = 3

return [9, 8, 9]

思想:从nums1中选择i个数,从nums2中选择k-i个数,使得合成的数最大。

分成两个子问题:

1. 如何从一个数组中选择i个数,使这i个数表示的数值是所有候选中最大的。

比如[9, 1, 2, 5, 8, 3] i = 2;如何得到 [9,8]。

2. 如何合并两个数组使得形成最大的值

比如[9, 8, 3] [6,5] ;如何得到[9,8,6,5,3]

Solution

To solve this problem, first let’s look at simpler version:

Easy Version No. 1

Given one array of length n, create the maximum number of length k.

The solution to this problem is Greedy with the help of stack. The recipe is as following

  • Initialize a empty stack
  • Loop through the array nums
    • pop the top of stack if it is smaller than nums[i] until
      1. stack is empty
      2. the digits left is not enough to fill the stack to size k
    • if stack size < k push nums[i]
  • Return stack

Since the stack length is known to be k, it is very easy to use an array to simulate the stack.
The time complexity is O(n) since each element is at most been pushed and popped once.

Java

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值