Rotate Array

For example, withn= 7 andk= 3, the array[1,2,3,4,5,6,7]is rotated to[5,6,7,1,2,3,4].


这道题Leetcode的compiler感觉有毒。。换了各种方法做都是beat 14%。。

我的方法跟这个类似: We use an extra array in which we place every element of the array at its correct position i.e. the number at indexiiin the original array is placed at the index(i+k). Then, we copy the new array to the original one.

不过官方答案里:a[(i+k)%nums.length]=nums[i]; 这行写的太漂亮。。。



用String Reverse版本的答案我最喜欢:

This approach is based on the fact that when we rotate the array k times,k elements from the back end of the array come to the front and the rest of the elements from the front shift backwards.

In this approach, we firstly reverse all the elements of the array. Then, reversing the first k elements followed by reversing the restn−kn−kelements gives us the required result.

这个属于一种经典解法,但是不是很容易看出来。【需要experienced 】

Original List                  : 1 2 3 4 5 6 7

After reversing all numbers    : 7 6 5 4 3 2 1

After reversing first k numbers : 5 6 7 4 3 2 1

After revering last n-k numbers : 5 6 7 1 2 3 4 --> Result

你可能感兴趣的:(Rotate Array)