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测试程序源码

  • 相关阅读:
    C语言位操作
    Ribbon负载规则的替换
    Nginx 的配置文件
    Nginx 操作常用的命令
    Nginx 是什么?
    SpringCloud Eureka 新版本依赖
    @Autowired 与@Resource的区别
    spring 注释
    redis 的 rdb 和 aof 持久化的区别
    jdk1.7下HashMap的头插法问题
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214777.html
Copyright © 2011-2022 走看看