Fastest algorithm for circle shift N sized array for M position

后端 未结 24 3057
温柔的废话
温柔的废话 2020-11-28 05:33

What is the fastest algorithm for circle shifting array for M positions?
For example, [3 4 5 2 3 1 4] shift M = 2 positions should be [1 4 3 4 5 2 3

24条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 05:54

    It's just a matter of representation. Keep the current index as an integer variable and when traversing the array use modulo operator to know when to wrap around. Shifting is then only changing the value of the current index, wrapping it around the size of the array. This is of course O(1).

    For example:

    int index = 0;
    Array a = new Array[SIZE];
    
    get_next_element() {
        index = (index + 1) % SIZE; 
        return a[index];
    }
    
    shift(int how_many) {
        index = (index+how_many) % SIZE;
    }
    

提交回复
热议问题