<LeetCode OJ> 189. Rotate Array
阿新 • • 發佈:2017-07-27
庫函數 flow icu col ren 2.6 article ace tex
或者調用庫函數來做(與上面的代碼全然等價),24ms:
189. Rotate Array
Total Accepted: 55073 Total Submissions: 278176 Difficulty: EasyRotate 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
<LeetCode OJ> 189. Rotate Array