from itertools import groupby
# 1. find the k-th and the last group with repeated items
pos = 0 # position in the array
repeated_group_count = 0
for _, group in groupby(array):
n = len(list(group))
pos += n
if n > 1: # found group with repeated items
last_start, last_end = pos - n, pos
repeated_group_count += 1
if repeated_group_count == k:
k_start, k_end = last_start, last_end
# 2. swap the k-th and the last group
if repeated_group_count > k:
array[:] = (array[:k_start]
+ array[last_start:last_end]
+ array[k_end:last_start]
+ array[k_start:k_end]
+ array[last_end:])
import re
def foo(array, k):
# Представим список как строку
array_str = ','.join(map(str, array))
seq_groups = re.findall(r'((\d)(,\2)+)', array_str)
if not seq_groups:
print('Not found groups')
# Найденные последовательности в списке
seq_groups = [seq for seq, _, _ in seq_groups]
print('groups:', seq_groups)
# Берем все группы после индекса k - 1 и из них выбираем первую
group_1 = seq_groups[k-1:][0]
# Берем последнюю группу
group_2 = seq_groups[-1]
# Замена одной группы на другую
array_str = array_str.replace(group_1, "__")
array_str = array_str.replace(group_2, group_1)
array_str = array_str.replace("__", group_2)
# Разбиваем список, приводим все элементы к числу, возвращаем как список
return list(map(int, array_str.split(',')))
算法:
k第 -th 和最后一系列重复元素的位置这是一种时间和内存线性算法。如果需要,您可以就地更换,无需额外的内存(例如,使用模拟
std::rotate())。在我看来,使用字符串会更容易,而且我还想记住正则表达式中的一个技巧:
考试: