189. Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

一刷
题解:
先全部reverse, 然后前面k个reverse, 然后最后len-k个reverse

public class Solution {
    public void rotate(int[] nums, int k) {
        k = k%nums.length;
        reverse(nums, 0, nums.length-1);
        reverse(nums, 0, k-1);
        reverse(nums, k, nums.length-1);
    }
    
    public void reverse(int[] nums, int left, int right){
        while(left<right){
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
            left++;
            right--;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • Rotate an array of n elements to the right by k steps. Fo...
    AlanGuo阅读 404评论 0 0
  • 哈哈哈哈哈
    如玉SH阅读 108评论 0 0
  • 周六堂哥带我去建外SOHO吃烧烤,也许是怕我在学校吃不好的原因吧,他总是会不定期带我出去开荤。在北京这个大...
    倉頡的字阅读 433评论 0 0
  • 追剧的时候,最直观的感觉是这部戏里没有几个正常人,都“有病”。也懂了《奶酪陷阱》的意思。海报上洪雪在一个看着像...
    Syfok阅读 1,507评论 1 5