LeetCode 题解工作台
使数组变成交替数组的最少操作数
给你一个下标从 0 开始的数组 nums ,该数组由 n 个正整数组成。 如果满足下述条件,则数组 nums 是一个 交替数组 : nums[i - 2] == nums[i] ,其中 2 。 nums[i - 1] != nums[i] ,其中 1 。 在一步 操作 中,你可以选择下标 i 并将 …
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
根据题目描述,我们可以知道,如果数组 是一个交替数组,那么数组中的奇数位置和偶数位置的元素一定是不同的,且奇数位置的元素相同,偶数位置的元素也相同。 要使得数组 变成交替数组的操作数最少,我们可以通过统计奇数位置和偶数位置的元素的出现次数,找到偶数位置出现次数最多的两个元素 和 ,以及对应的出现次数 和 ;再找到奇数位置出现次数最多的两个元素 和 ,以及对应的出现次数 和 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的数组 nums ,该数组由 n 个正整数组成。
如果满足下述条件,则数组 nums 是一个 交替数组 :
nums[i - 2] == nums[i],其中2 <= i <= n - 1。nums[i - 1] != nums[i],其中1 <= i <= n - 1。
在一步 操作 中,你可以选择下标 i 并将 nums[i] 更改 为 任一 正整数。
返回使数组变成交替数组的 最少操作数 。
示例 1:
输入:nums = [3,1,3,2,4,3] 输出:3 解释: 使数组变成交替数组的方法之一是将该数组转换为 [3,1,3,1,3,1] 。 在这种情况下,操作数为 3 。 可以证明,操作数少于 3 的情况下,无法使数组变成交替数组。
示例 2:
输入:nums = [1,2,2,2,2] 输出:2 解释: 使数组变成交替数组的方法之一是将该数组转换为 [1,2,1,2,1]. 在这种情况下,操作数为 2 。 注意,数组不能转换成 [2,2,2,2,2] 。因为在这种情况下,nums[0] == nums[1],不满足交替数组的条件。
提示:
1 <= nums.length <= 1051 <= nums[i] <= 105
解题思路
方法一:维护奇偶位置的计数
根据题目描述,我们可以知道,如果数组 是一个交替数组,那么数组中的奇数位置和偶数位置的元素一定是不同的,且奇数位置的元素相同,偶数位置的元素也相同。
要使得数组 变成交替数组的操作数最少,我们可以通过统计奇数位置和偶数位置的元素的出现次数,找到偶数位置出现次数最多的两个元素 和 ,以及对应的出现次数 和 ;再找到奇数位置出现次数最多的两个元素 和 ,以及对应的出现次数 和 。
如果 ,那么我们可以将数组 中偶数位置的元素全部变成 ,奇数位置的元素全部变成 ,这样操作数为 ;如果 ,那么我们可以将数组 中偶数位置的元素全部变成 ,奇数位置的元素全部变成 ,或者将数组 中偶数位置的元素全部变成 ,奇数位置的元素全部变成 ,这样操作数为 。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
def f(i: int) -> Tuple[int, int, int, int]:
k1 = k2 = 0
cnt = Counter(nums[i::2])
for k, v in cnt.items():
if cnt[k1] < v:
k2, k1 = k1, k
elif cnt[k2] < v:
k2 = k
return k1, cnt[k1], k2, cnt[k2]
a, b = f(0), f(1)
n = len(nums)
if a[0] != b[0]:
return n - (a[1] + b[1])
return n - max(a[1] + b[3], a[3] + b[1])
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
This problem tests the ability to work with arrays and hash tables efficiently.
- question_mark
Check the candidate's ability to optimize solutions using counting techniques.
- question_mark
Look for a clear understanding of how to handle alternating sequence constraints.
常见陷阱
外企场景- error
Failing to split the array into odd and even indexed groups properly.
- error
Not considering swapping the most frequent elements when they overlap.
- error
Misunderstanding the number of operations needed when both the odd and even indexed groups share common elements.
进阶变体
外企场景- arrow_right_alt
Using different methods for frequency counting.
- arrow_right_alt
Handling larger input sizes efficiently.
- arrow_right_alt
Considering edge cases like arrays of length 1 or 2.