def move(ls: list, offset):
"""
元素原索引+位移数(正为右移,负为左移)之和求关于数组长度(数组的模)的余数,即为位移后的元素索引。
再对新索引升序排序,去除索引,即为位移后的新数组
:param ls:
:param offset:
:return:
"""
mod = len(ls)
ids = [[(item[0]+offset)%mod, item[1]] for item in enumerate(ls)]
ids.sort(key=lambda item: item[0])
return [item[1] for item in ids]
def move2(ls: list, offset):
"""
分段反转,以位移数(对模求余)为界,分别反转两个子数组,再整体反转
:param ls:
:param offset:
:return:
"""
mod = len(ls)
offset = offset % mod
tail = list(reversed(ls[mod-offset:]))
head = list(reversed(ls[:mod-offset]))
return list(reversed(head+tail))
if __name__ == '__main__':
nums = [8, 9, 10, 11]
print(move(nums, 1))
print(move2(nums, 1))
print(move(nums, -1))
print(move2(nums, -1))
"""
[11, 8, 9, 10]
[11, 8, 9, 10]
[9, 10, 11, 8]
[9, 10, 11, 8]
"""
python--数组平移K位
最新推荐文章于 2023-06-27 11:23:28 发布