• Leetcode-189 Rotate Array


    #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.

    [show hint]

    Hint:
    Could you do it in-place with O(1) extra space?

    题解:最容易想到的是右移k次,用最容易想到的方法,结果是超时,时间复杂度是O(kn).

    class Solution {
    public:
        void rotate(vector<int>& nums, int k) {
           
            int n=nums.size();
            
            while(k--)
            {
               rightShift(nums);
            }
        }
        void rightShift(vector<int>& nums)
        {
            int temp=0;
            temp=nums[nums.size()-1];
            for(int i=nums.size()-1;i>0;i--)
            {
                nums[i]=nums[i-1];
            }
            nums[0]=temp;
        }
    };

    只好换三步反转法来做,时间复杂度是O(n),空间复杂度是O(1)

    class Solution {
    public:
        void rotate(vector<int>& nums, int k) {
            int n=nums.size();
            k=k%n;
            if(k==0)
                return ;
                
            reverseString(nums,0,n-k-1);
            reverseString(nums,n-k,n-1);
            reverseString(nums,0,n-1);
        }
        void reverseString(vector<int>& nums,int from,int to)
        {
            while(from<to)
            {
                int temp=nums[from];
                nums[from++]=nums[to];
                nums[to--]=temp;
            }
        }
    };

  • 相关阅读:
    excel unixtime与北京时间互转
    vim的漫漫长征路
    const常量
    第一章:绪论
    2.4奇偶校验
    2.3数据校验的基本原理
    2.2定点与浮点数据表示
    2.1机器数及其特点
    1.2计算机系统性能评价
    冯诺依曼结构原理及层次分析
  • 原文地址:https://www.cnblogs.com/fengxw/p/6085700.html
Copyright © 2020-2023  润新知