zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】数组题9:旋转数组(189. Rotate Array)

    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    189. Rotate Array(相当于循环右移k位)

    Given an array, rotate the array to the right by k steps, where k is non-negative.
    Example 1:
    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]
    Example 2:
    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?
    相关题目:循环左移
    //方法一:使用额外的数组,索引i用i+k替换,然后把组织好的数组复制过去
    // O(n), O(n)
    /*class Solution
    {
    public:
        void rotate(vector<int>& a, int k)
        {
            vector<int> temp(a);
            int n = a.size();
            for(int i = 0; i<n; i++)
            {
                temp[(i+k)%n] = a[i]; //进行题意的rotated
            }
           
            a = temp; //将数据复制过去
        }
    };*/
    /*
    方法二:多次反转法
    Original List                   : 1 2 3 4 5 6 7
    After reversing all numbers     : 7 6 5 4 3 2 1
    After reversing first k numbers : 5 6 7 4 3 2 1
    After revering last n-k numbers : 5 6 7 1 2 3 4 --> Result
    分析:O(n) O(1)
    */
    #include <algorithm>
    class Solution
    {
    public:
        void rotate(vector<int>& a, int k)
        {
            k %= a.size(); //以免k过大
           
            reverse(a.begin(), a.end()); //反转所有元素
            reverse(a.begin(), a.begin()+k); //反转前k个元素
            reverse(a.begin()+k, a.end()); //反转剩余元素(注意reverse反转区间为前闭后开,故这里为a.begin()+k)
        }
    };
    //方法三:使用循环替代,略
     
     
     
  • 相关阅读:
    5.颜色空间转换
    Linux下的解压命令
    4.图像模糊/图像平滑
    insightface作者提供数据训练解读
    MXNetError: [05:53:50] src/operator/nn/./cudnn/cudnn_convolution-inl.h:287
    python中import cv2遇到的错误及安装方法
    docker 安装 mxnet
    95. Unique Binary Search Trees II
    236. Lowest Common Ancestor of a Binary Tree
    124. Binary Tree Maximum Path Sum
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10224335.html
Copyright © 2011-2022 走看看