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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容