[Leetcode]11 Rotate Array

Rotate Array

题目连接:https://oj.leetcode.com/problems/rotate-array/
Runtimes:26ms

1、问题

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.

2、分析

最传统的想法当然是用O(n)的空间,按照第i个数放在(i+k)%n的位置上来操作。但是题目要求是只用O(1)的空间,那么想到可以用逆序的操作,首先进行一次全范围逆序,然后再分别在0~(k-1),k~(n-1)的范围内进行逆序,最终得到解。

3、小结

整个过程需要三次逆序,时间复杂度为O(n),逆序时只消耗O(1)的空间。

4、实现
    class Solution {
public:
    void reverse(int nums[], int sta, int end)
    {
        for(int i = sta, j = end; i < j; i++, j--)
        {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }

    void rotate(int nums[], int n, int k) {
        k = k % n;
        if(k == 0)
            return;
        reverse(nums, 0, n - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, n - 1);
    }
};
5、三思

这道题比较简单,话说题目要求弄至少三种解法,容我三思一下哈。
参考链接:http://leetcode.com/2010/04/rotating-array-in-place.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值