Cyclic shift algorithm

Cyclic shift method

Reference article: content connector . Mainly from the arrays, strings, lists three cases, introduce specific implementation of the cyclic shift. Here only sort out what the article context.

Array cyclic shift

Method a: Method modulo

This method has been used in Leetcode 189, the authors considered here two new cases:

  • If the shift amount K is the length of the array len (s) of a multiple, then it is not shifted;
  • If K is negative, that is, in the opposite direction (to the left)

Modulo method due to the need to open up a new array of length len (s), this will increase the space overhead algorithm, does not meet the space O (1) algorithm situ.

Method two: time for space

If you want to solve the above problem, then we will consider again and again, moving a total of K times. Thus the time complexity becomes O (N * K), up to O (N ^ 2).

Method three: space for time

That is, the array length becomes doubled, to fight together. This leetcode-189 also has a related description.

Three Reversal Method

The so-called "flip", such as [0, N], and N 0 is the exchange position, and an exchange position (N-1) ....... Algorithm Description:

  • First [0, n - k - 1] Flip
  • Then [n - k, n - 1] Flip
  • Finally [0, n - 1] reversed
    this algorithm is actually very good proof. We use the representative direction of the arrow, the initial array is A-> B | C-> D; after inversion into a first two B <-A | D <-C; and finally entirely turned, C-> D | A- > B. Flip like to see the direction of the arrow, it is they want more intuitive proof. As described flip implementation code:
while (start < end) {
    t = list[start];
    list[start] = list[end];
    list[end] = t;
    start++;
    end--;
}

String shift

Here are examples of questions to check whether it contains. Intuitive solution is to move every time it is judged again, it is necessary to determine len (s) times.

Violence Act

It is the most intuitive way to the top. The idea is to achieve: known S1 and S2, S1 to the left every time a start of two strings inspection start pointer P1 and P2; one, two loop checks every pointer left.

With space for time

Splicing two strings S1 and then starts a new two pointers S1 and S2 to be checked.

Method modulo

Method for modulo space for actually tricky time of the algorithm. We also a back S1 S1 illusion, a method is actually realized modulo.

Cyclic shift list

From leetcode-61, medium difficulty. There was never launched.

Guess you like

Origin www.cnblogs.com/rongyupan/p/12630051.html