zoukankan      html  css  js  c++  java
  • LeetCode(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?
    Related problem: Reverse Words in a String II

    Credits:
    Special thanks to @Freezen for adding this problem and creating all test cases.

    分析

    数组旋转问题。

    给定一个序列和一个整数,要求将序列元素右旋k位。题目不难,但是需要注意的一点是k值可能大于序列长度,所以,旋转之前先求k对序列长度size的余数即可。

    该题目一个简单的解决方法是三次反转:

    1. 将序列中(0 , size-k-1)元素反转;
    2. 将序列中(size-k , size-1)元素反转;
    3. 将全序列(0,size-1)反转;

      即可完成要求!

    AC代码

    class Solution {
    public:
        void rotate(vector<int>& nums, int k) {
            if (nums.empty())
                return;
    
            int size = nums.size();
    
            //确定最终右旋元素个数
    
            k %= size;
    
            vector<int>::iterator beg = nums.begin();
            //旋转0~(size-k) (size-k , size);
            reverse(beg, beg + size - k);
            reverse(beg + size - k, nums.end());
            //最后一次全部反转,即可完成
            reverse(beg, nums.end());
        }
    };
    

    GitHub测试程序源码

  • 相关阅读:
    SVG的学习(34—36)
    28-30 js 文本全选
    28-30 键盘事件
    react学习(四)之设置 css样式 篇
    跳台阶
    详解Django的CSRF认证
    Django model中数据批量导入bulk_create()
    Redis从入门到精通
    Python的进阶1:copy()与deepcopy()区别
    sql面试题
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214777.html
Copyright © 2011-2022 走看看