Total Accepted: 55073 Total
Submissions: 278176 Difficulty: Easy
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.
第一种方法:
申请额外vector来处理,24ms
题目要求用三种方法
第一种:申请额外空间O(N),用vector直接处理
找规律:原数组中i位置的数据就是tmpnums中(i+k+len)/ len的数据
class Solution { public: void rotate(vector<int>& nums, int k) { k=k%nums.size(); //k可能大于size vector<int> tmpnums(nums.size()); for (int i=0;i<nums.size();i++) tmpnums[(i+k+nums.size())%nums.size()]=nums[i]; nums=tmpnums; } };
另外一种方法:
技巧法(逆序),没有申请额外空间,24ms
另外一种:题目意思说能够原地处理
先前面nums.size()-k个数据逆序,接着整个数组总体逆序。最后将前k个数逆序
举例:4,3,2,1,5,6,7-------》7,6,5,1,2,3,4--------》5,6,7,1,2,3,4
class Solution { public: void rotate(vector<int>& nums, int k) { k=k%nums.size(); for (int i=0;i<(nums.size()-k)/2;i++) { int tmp1=nums[i]; nums[i]=nums[nums.size()-k-1-i]; nums[nums.size()-k-1-i]=tmp1; } for (int i=0;i<nums.size()/2;i++) { int tmp1=nums[i]; nums[i]=nums[nums.size()-1-i]; nums[nums.size()-1-i]=tmp1; } for (int i=0;i<k/2;i++) { int tmp1=nums[i]; nums[i]=nums[k-1-i]; nums[k-1-i]=tmp1; } } };
或者调用库函数来做(与上面的代码全然等价),24ms:
class Solution { public: void rotate(vector<int>& nums, int k) { k=k%nums.size(); vector<int> ::iterator ite=nums.begin(); reverse(ite,ite+nums.size()-k); reverse(ite,ite+nums.size()); reverse(ite,ite+k); } };
第三种方法:
循环左移或者右移(O(N*K)超时)
class Solution { public: void MoveRightByOne(vector<int>& nums) { int temp = nums[ nums.size() - 1]; for (int i = nums.size() - 1; i >=1 ; --i) { nums[i] = nums[i - 1]; } nums[0] = temp; } void MoveLeftByOne(vector<int>& nums) { int temp = nums[0]; for (int i = 0; i < nums.size()-1 ; ++i) { nums[i] = nums[i + 1]; } nums[nums.size() - 1] = temp; } void rotate(vector<int>& nums ,int k) { k = k % nums.size(); if (k < nums.size()/2) { for (int i = 0; i < k; ++i) MoveRightByOne(nums); } else { for (int i = 0; i < nums.size()-k; ++i) MoveLeftByOne(nums); } } };
注:本博文为EbowTang原创,兴许可能继续更新本文。假设转载。请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50449688
原作者博客:http://blog.csdn.net/ebowtang