美文网首页
Rotate Array

Rotate Array

作者: BigBig_Fish | 来源:发表于2017-07-05 21:55 被阅读0次

    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.

    题目分析

    将整个数组向右移动k位,那么第i位的目标位置就是(i+k)%len

    代码

    class Solution {
    public:
        void rotate(vector<int>& nums, int k) {
            vector<int> vec(nums);
            int len=nums.size();
            for(int i=0; i<len; i++) {
                nums[(i+k)%len] = vec[i];
            }
            return ;
        }
    };
    

    倒置的思路

    将后k位倒置和前n-k位倒置,然后将整个数组倒置

    class Solution 
        {
        public:
            void rotate(int nums[], int n, int k) 
            {
                k = k%n;
        
                // Reverse the first n - k numbers.
                // Index i (0 <= i < n - k) becomes n - k - i.
                reverse(nums, nums + n - k);
                
                // Reverse tha last k numbers.
                // Index n - k + i (0 <= i < k) becomes n - i.
                reverse(nums + n - k, nums + n);
                
                // Reverse all the numbers.
                // Index i (0 <= i < n - k) becomes n - (n - k - i) = i + k.
                // Index n - k + i (0 <= i < k) becomes n - (n - i) = i.
                reverse(nums, nums + n);
            }
        };
    

    相关文章

      网友评论

          本文标题:Rotate Array

          本文链接:https://www.haomeiwen.com/subject/uecchxtx.html