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.

看到这道题就想到了以前做字符串旋转是一样的方法,其中比较好的解就是三步反转,这样能比使用将一个一个元素移动的时间复杂度低很多,若是使用上述一个一个移动,那么对于长度为n的数组,假设需要移动m个元素,那么总共需要m*n次操作,同时还需要设立一个变量来保存第一个元素,那么时间复杂度为O(mn),空间复杂度为O(1)。

实现代码:

public class RotateArray {

    public void rotate(int[] nums, int k) {

        int m = nums.length;
        k %= m;

        reverserString(nums, 0, m-k-1);
        reverserString(nums, m-k, m-1);
        reverserString(nums, 0, m-1);
    }




    public void reverserString(int[] nums, int n, int m){
        while(n < m){
            int num = nums[n];
            nums[n++] = nums[m];
            nums[m--] = num;
        }
    }

    public static void main(String[] args){
        int[] nums = {1,2,3,4,5,6,7};

        new RotateArray().rotate(nums,3);

        for (int num : nums) {
            System.out.println("num = " + num);
        }

    }

上面三次反转的过程:

这里写图片描述


这种方法的时间复杂度为O(n),空间复杂度为O(1),虽然这道题比较基础,但是却能体现了对数组结构的一个理解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值