美文网首页
189 Rotate Array

189 Rotate Array

作者: 烟雨醉尘缘 | 来源:发表于2019-06-18 14:07 被阅读0次

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example:

Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Note:

Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?

解释下题目:

数组的数字往后推移k位,如果超出了最后则接到头部

1. 倒置的方法

实际耗时:0ms

    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);
    }

    private void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int tmp = nums[start];
            nums[start] = nums[end];
            nums[end] = tmp;
            start++;
            end--;
        }
    }
踩过的坑:[-1] k=2

  我自己想到的思路是有三种,第一种是,搞个函数,然后这个函数的作用是每次给数组后退1格,然后如果是k的话就重复k次,这样时间是O(nk) 不需要额外的空间。第二种是再开辟一个同样大小的数组,很简单。最后一种就是上面代码里的,其实这种rotate的题目最后都可以用倒序来实现。

时间复杂度O(n)
空间复杂度O(1)

表名1 表名2

相关文章

网友评论

      本文标题:189 Rotate Array

      本文链接:https://www.haomeiwen.com/subject/ynkfqctx.html