leetcode-189. Rotate Array

来源:互联网 发布:管家婆数据导入工具 编辑:程序博客网 时间:2024/04/30 07:27

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.

思路:字符串右移操作,(x^ty^t)^t = yx

class Solution {    //思路:《程序员编程艺术第一~二十七章集锦与总结(教你如何编程)(by_July)定稿版》原题    // (X^tY^t)^t = YX;public:    void rotate(vector<int>& nums, int k) {        int length = nums.size();        k = k%length;        reversalNum(nums,0,length-k-1);        reversalNum(nums,length-k,length-1);        reversalNum(nums,0,length-1);    }    void reversalNum(vector<int>& nums,int begin,int end)    {        int temp;        while(begin < end)        {            temp = nums[begin];            nums[begin] = nums[end];            nums[end] = temp;            begin++;            end--;        }    }};
0 0
原创粉丝点击