LeetCode 题解工作台
连接二进制表示可形成的最大数值
给你一个长度为 3 的整数数组 nums 。 现以某种顺序 连接 数组 nums 中所有元素的 二进制表示 ,请你返回可以由这种方法形成的 最大 数值。 注意 任何数字的二进制表示 不含 前导零。 示例 1: 输入: nums = [1,2,3] 输出: 30 解释: 按照顺序 [3, 1, 2] …
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·结合·位运算·操作
答案摘要
根据题目描述,数组 的长度为 ,我们可以枚举 的全排列,一共有 $3! = 6$ 种排列方式,然后将排列后的数组中的元素转换为二进制字符串,再将这些二进制字符串连接起来,最后将连接后的二进制字符串转换为十进制数,取最大值即可。 时间复杂度 $O(\log M)$,其中 表示 中的元素的最大值。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·位运算·操作 题型思路
题目描述
给你一个长度为 3 的整数数组 nums。
现以某种顺序 连接 数组 nums 中所有元素的 二进制表示 ,请你返回可以由这种方法形成的 最大 数值。
注意 任何数字的二进制表示 不含 前导零。
示例 1:
输入: nums = [1,2,3]
输出: 30
解释:
按照顺序 [3, 1, 2] 连接数字的二进制表示,得到结果 "11110",这是 30 的二进制表示。
示例 2:
输入: nums = [2,8,16]
输出: 1296
解释:
按照顺序 [2, 8, 16] 连接数字的二进制表述,得到结果 "10100010000",这是 1296 的二进制表示。
提示:
nums.length == 31 <= nums[i] <= 127
解题思路
方法一:枚举
根据题目描述,数组 的长度为 ,我们可以枚举 的全排列,一共有 种排列方式,然后将排列后的数组中的元素转换为二进制字符串,再将这些二进制字符串连接起来,最后将连接后的二进制字符串转换为十进制数,取最大值即可。
时间复杂度 ,其中 表示 中的元素的最大值。空间复杂度 。
class Solution:
def maxGoodNumber(self, nums: List[int]) -> int:
ans = 0
for arr in permutations(nums):
num = int("".join(bin(i)[2:] for i in arr), 2)
ans = max(ans, num)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is constant O(6) due to fixed 3-element array, as all permutations are evaluated. Space complexity is also O(1) aside from temporary binary strings, since only the maximum value is stored. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Consider all 3! permutations to avoid missing the maximum binary concatenation.
- question_mark
Binary conversion should exclude leading zeros to match correct decimal output.
- question_mark
Optimal solution leverages small array size and direct permutation checks rather than sorting heuristics.
常见陷阱
外企场景- error
Adding leading zeros to binary strings can yield incorrect numeric results.
- error
Forgetting to check all six permutations may miss the true maximum.
- error
Attempting complex bit manipulation tricks for a fixed small array wastes time.
进阶变体
外企场景- arrow_right_alt
Extend to arrays longer than 3, requiring more efficient ordering or greedy heuristics.
- arrow_right_alt
Allow repeated numbers and check whether duplicate permutations affect the result.
- arrow_right_alt
Maximize binary concatenation but return the binary string instead of decimal.