首页 > 学院 > 开发设计 > 正文

189. Rotate Array

2019-11-08 02:37:34
字体:
来源:转载
供稿:网友

题目

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]

Related problem: Reverse Words in a String II

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

Subscribe to see which companies asked this question.


思路

思路:《程序员编程艺术第一~二十七章集锦与总结(教你如何编程)(by_July)定稿版》原题 计算公式:(X^tY^t)^t = YX;


代码

class Solution {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--; } }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表