LeetCode 题解工作台
判断一个数组是否可以变为有序
给你一个下标从 0 开始且全是 正 整数的数组 nums 。 一次 操作 中,如果两个 相邻 元素在二进制下 设置位 的数目 相同 ,那么你可以将这两个元素交换。你可以执行这个操作 任意次 ( 也可以 0 次 )。 如果你可以使数组变为非降序,请你返回 true ,否则返回 false 。 示例 1…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·结合·位运算·操作
答案摘要
我们可以使用双指针,将数组 分成若干个子数组,每个子数组中的元素的二进制表示中 的个数相同。对于每个子数组,我们只需要关注它的最大值和最小值,如果最小值比上一个子数组的最大值小,那么就无法通过交换使得数组有序。 时间复杂度 ,其中 是数组 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·位运算·操作 题型思路
题目描述
给你一个下标从 0 开始且全是 正 整数的数组 nums 。
一次 操作 中,如果两个 相邻 元素在二进制下 设置位 的数目 相同 ,那么你可以将这两个元素交换。你可以执行这个操作 任意次 (也可以 0 次)。
如果你可以使数组变为非降序,请你返回 true ,否则返回 false 。
示例 1:
输入:nums = [8,4,2,30,15] 输出:true 解释:我们先观察每个元素的二进制表示。 2 ,4 和 8 分别都只有一个数位为 1 ,分别为 "10" ,"100" 和 "1000" 。15 和 30 分别有 4 个数位为 1 :"1111" 和 "11110" 。 我们可以通过 4 个操作使数组非降序: - 交换 nums[0] 和 nums[1] 。8 和 4 分别只有 1 个数位为 1 。数组变为 [4,8,2,30,15] 。 - 交换 nums[1] 和 nums[2] 。8 和 2 分别只有 1 个数位为 1 。数组变为 [4,2,8,30,15] 。 - 交换 nums[0] 和 nums[1] 。4 和 2 分别只有 1 个数位为 1 。数组变为 [2,4,8,30,15] 。 - 交换 nums[3] 和 nums[4] 。30 和 15 分别有 4 个数位为 1 ,数组变为 [2,4,8,15,30] 。 数组变成有序的,所以我们返回 true 。 注意我们还可以通过其他的操作序列使数组变得有序。
示例 2:
输入:nums = [1,2,3,4,5] 输出:true 解释:数组已经是非降序的,所以我们返回 true 。
示例 3:
输入:nums = [3,16,8,4,2] 输出:false 解释:无法通过操作使数组变为非降序。
提示:
1 <= nums.length <= 1001 <= nums[i] <= 28
解题思路
方法一:双指针
我们可以使用双指针,将数组 分成若干个子数组,每个子数组中的元素的二进制表示中 的个数相同。对于每个子数组,我们只需要关注它的最大值和最小值,如果最小值比上一个子数组的最大值小,那么就无法通过交换使得数组有序。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def canSortArray(self, nums: List[int]) -> bool:
pre_mx = 0
i, n = 0, len(nums)
while i < n:
cnt = nums[i].bit_count()
j = i + 1
mi = mx = nums[i]
while j < n and nums[j].bit_count() == cnt:
mi = min(mi, nums[j])
mx = max(mx, nums[j])
j += 1
if pre_mx > mi:
return False
pre_mx = mx
i = j
return True
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because each element is processed once for bit counting and segment sorting. Space complexity is O(n) due to storing groups of elements by set bit counts. |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Look for opportunities to segment the array by set bit counts.
- question_mark
Check if sorting within segments can lead to global ascending order.
- question_mark
Ask candidates about efficient ways to count set bits and map numbers to segments.
常见陷阱
外企场景- error
Assuming any adjacent swap is allowed without checking set bit counts.
- error
Overlooking that segments must maintain their original relative positions.
- error
Failing to verify that the concatenated sorted segments form a fully ascending array.
进阶变体
外企场景- arrow_right_alt
Allow swaps for elements with set bits differing by one instead of exactly equal.
- arrow_right_alt
Determine the minimum number of swaps required to sort the array under the same rules.
- arrow_right_alt
Apply the same approach to arrays of larger integers with more than 28 bits.