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

    一:三次翻转,c++stl中就有这个算法

    class Solution {
    public:
        void reverse(vector<int>& nums,int startPos,int endPos)
        {
            int i=startPos,j=endPos-1;
            while(i<j){
                int tmp = nums[i];
                nums[i] = nums[j];
                nums[j] = tmp;
                i++;j--;
            }
        }
        void rotate(vector<int>& nums, int k) {
            if(k<=0){
                return;
            }
            int numsSize = nums.size();
            k = k%numsSize;
            reverse(nums,0,numsSize-k);
            reverse(nums,numsSize-k,numsSize);
            reverse(nums,0,numsSize);
        }
    };

    2:使用一个辅助空间O(k)的辅助空间

    代码不多说,太简单

    3:递推计算每个字符的位置,循环n次

    class Solution {
    public:
        void rotate(vector<int>& nums, int k) {
            if(k<=0){
                return;
            }
            int numsSize = nums.size();
            int start = 0,i=0;
            while(i<numsSize){
                int nextIndex = (start+k)%numsSize;
                int curVal = nums[start];
                while(nextIndex!=start){
                    int tmp = nums[nextIndex];
                    nums[nextIndex] = curVal;
                    curVal = tmp;
                    nextIndex = (nextIndex+k)%numsSize;
                    i++;
                }
                nums[nextIndex] = curVal;
                i++;
                start++;
            }
        }
    };
  • 相关阅读:
    CCLayerColor 用法
    数据存储的常见方式
    rand() 和arc4random()到底应该如何取舍呢
    Cocos2d 中对图片的各种操作
    objectivec 解压缩zip
    设置IE浏览器默认的下载路径
    设置浏览器主页
    得到所有本机上安装的软件名
    取消快捷方式中的箭头图标
    查看本机服务
  • 原文地址:https://www.cnblogs.com/zengzy/p/4959358.html
Copyright © 2020-2023  润新知