📅  最后修改于: 2023-12-03 15:10:44.881000             🧑  作者: Mango
“最小更改”指的是对数组进行修改,使得数组中包含 k 个不同的元素,且修改次数最少。
思路:
代码片段:
def minChanges(nums: List[int], k: int) -> int:
n = len(nums)
max_val = 2 ** 10
f = [float("inf")] * max_val
f[0] = 0
for i in range(k):
cnt = Counter(nums[i::k])
t2min = min(f)
g = [t2min] * max_val
for x, cx in cnt.items():
for j in range(max_val):
g[x ^ j] = min(g[x ^ j], f[j] - cx)
f = [val + t2 for val, t2 in zip(g, [cnt[x] for x in range(max_val)])]
# print(f, g)
return f[0]
思路:
代码片段:
def minChanges(nums: List[int], k: int) -> int:
n = len(nums)
max_val = 2 ** 10
f = [float("inf")] * max_val
f[0] = 0
for i in range(k):
cnt = Counter(nums[i::k])
t2min = min(f)
g = [t2min] * max_val
for x, cx in cnt.items():
for j in range(max_val):
g[x ^ j] = min(g[x ^ j], f[j] - cx)
f = [val + t2 for val, t2 in zip(g, [cnt[x] for x in range(max_val)])]
# print(f, g)
return f[0]
以上两种方法都是在遍历数组的基础上,通过不同的思路进行修改。哈希表方法适用于小规模数据,时间复杂度为 O(nk),空间复杂度也是 O(nk);滑动窗口方法适用于大规模数据,时间复杂度为 O(n),空间复杂度为常数级别。