Algorithm to rotate an array in linear time

后端 未结 22 2122
我寻月下人不归
我寻月下人不归 2020-11-28 05:05

How to rotate an integer array by i times using swap function only in linear time.

22条回答
  •  野性不改
    2020-11-28 06:00

    An O(1) method of accomplishing this, in python:

    class OffsetList(list):
        __slots__ = 'offset'
        def __init__(self, init=[], offset=-1):
            super(OffsetList, self).__init__(init)
            self.offset = offset
        def __getitem__(self, key):
            return super(OffsetList, self).__getitem__(key + self.offset)
        def __setitem__(self, key, value):
            return super(OffsetList, self).__setitem__(key + self.offset, value)
        def __delitem__(self, key):
            return super(OffsetList, self).__delitem__(key + self.offset)
        def index(self, *args):
            return super(OffsetList, self).index(*args) - self.offset
    

    This is based on this answer about using a 1-based list in python.

    This does have the slight glitch that if you attempt to index an item off the end of the list, it will return items from the (new) beginning, and negative indicies less than the size minus the offset won't work.

提交回复
热议问题