C/C++ - efficient method of rotating an array without using build-in functions (homework)

前端 未结 2 1776
情书的邮戳
情书的邮戳 2021-01-19 18:02

The task is to rotate left or rotate right a subarray of an array given number of times.

Let me explain this on an example:

  • lets data be an array.
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-19 18:34

    There's a trick to this. It's pretty weird that you'd get this for homework if the trick wasn't mentioned in class. Anyway...

    To rotate a sequence of N elements left by M:

    • reverse the whole sequence
    • reverse the last M elements
    • reverse the first N-M elements

    done

    e.g. left by 2: 1234567 -> 7654321 -> 7654312 -> 3456712

提交回复
热议问题